package com.example.sunmiv1.activity.good;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.NumberKeyListener;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.RemoteInput;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.activity.ClassificationActivity;
import com.example.sunmiv1.activity.MainActivity;
import com.example.sunmiv1.adapter.SkuGoodsAdapter;
import com.example.sunmiv1.adapter.good.GridImageAdapter;
import com.example.sunmiv1.base.BaseActivity;
import com.example.sunmiv1.entity.CurrencyInfo;
import com.example.sunmiv1.entity.EditSet;
import com.example.sunmiv1.entity.LoginEntity;
import com.example.sunmiv1.entity.SkuGoodsInfo;
import com.example.sunmiv1.entity.SkuInfoNew;
import com.example.sunmiv1.entity.good.NewGoodInfo;
import com.example.sunmiv1.fragment.ChooseTagDialogFragment;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.good.FullyGridLayoutManager;
import com.example.sunmiv1.utils.good.GlideEngine;
import com.example.sunmiv1.utils.net.ACache;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.LoadingDialog;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.example.sunmiv1.utils.video.FileSize;
import com.example.sunmiv1.utils.zxing.Constant;
import com.example.sunmiv1.utils.zxing.activity.CaptureActivity;
import com.example.sunmiv1.views.MyListView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.iceteck.silicompressorr.SiliCompressor;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.luck.picture.lib.tools.ScreenUtils;
import com.luck.picture.lib.tools.SdkVersionUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.io.File;
import java.io.FileInputStream;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.example.sunmiv1.activity.good.GoodsManageActivity.sellcountBean;
import static com.iceteck.silicompressorr.SiliCompressor.with;


public class NewAddGoodActivity extends BaseActivity implements ChooseTagDialogFragment.FragmentHook {


    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.newAddGood_name)
    EditText newAddGoodName;
    @BindView(R.id.newAddGood_freightNumber)
    EditText newAddGoodFreightNumber;
    @BindView(R.id.newAddGood_code)
    EditText newAddGoodCode;
    @BindView(R.id.newAddGood_barcodeIv)
    ImageView newAddGoodBarcodeIv;
    @BindView(R.id.newAddGood_classification_name)
    TextView newAddGoodClassificationName;
    @BindView(R.id.newAddGood_classification)
    LinearLayout newAddGoodClassification;
    @BindView(R.id.newAddGood_retailPrice)
    EditText newAddGoodRetailPrice;
    @BindView(R.id.newAddGood_shopPrice)
    EditText newAddGoodShopPrice;
    @BindView(R.id.newAddGood_cover)
    RecyclerView newAddGoodCover;
    @BindView(R.id.newAddGood_video)
    RecyclerView newAddGoodVideo;
    @BindView(R.id.newAddGood_banner)
    RecyclerView newAddGoodBanner;
    @BindView(R.id.newAddGood_pluIndex)
    EditText newAddGoodPluIndex;
    @BindView(R.id.newAddGood_isWeight)
    Switch newAddGoodIsWeight;
    @BindView(R.id.newAddGood_skuSetting)
    LinearLayout newAddGoodSkuSetting;
    @BindView(R.id.newAddGood_isSerial)
    Switch newAddGoodIsSerial;
    @BindView(R.id.newAddGood_isSku)
    Switch newAddGoodIsSku;
    @BindView(R.id.addGoods_is_skuLin)
    LinearLayout addGoodsIsSkuLin;
    @BindView(R.id.newAddGood_skuGoodsListView)
    MyListView newAddGoodSkuGoodsListView;
    @BindView(R.id.newAddGood_skuGoodsLin)
    LinearLayout newAddGoodSkuGoodsLin;
    @BindView(R.id.newAddGood_delivery1)
    CheckBox newAddGoodDelivery1;
    @BindView(R.id.newAddGood_delivery2)
    CheckBox newAddGoodDelivery2;
    @BindView(R.id.newAddGood_delivery3)
    CheckBox newAddGoodDelivery3;
    @BindView(R.id.newAddGood_deliveryTemplate)
    Spinner newAddGoodDeliveryTemplate;
    @BindView(R.id.newAddGood_status)
    Switch newAddGoodStatus;
    @BindView(R.id.newAddGood_retailState)
    Switch newAddGoodRetailState;
    @BindView(R.id.newAddGood_onlineState)
    Switch newAddGoodOnlineState;
    @BindView(R.id.newAddGood_advanceSaleStatus)
    Switch newAddGoodAdvanceSaleStatus;
    @BindView(R.id.newAddGood_splitState)
    Switch newAddGoodSplitState;
    @BindView(R.id.newAddGood_refundState)
    Switch newAddGoodRefundState;
    @BindView(R.id.newAddGood_exchangeState)
    Switch newAddGoodExchangeState;
    @BindView(R.id.newAddGood_subheading)
    EditText newAddGoodSubheading;
    @BindView(R.id.newAddGood_purchasePrice)
    EditText newAddGoodPurchasePrice;
    @BindView(R.id.newAddGood_brand)
    Spinner newAddGoodBrand;
    @BindView(R.id.newAddGood_label_lin)
    LinearLayout newAddGoodLabelLin;
    @BindView(R.id.newAddGood_label)
    Spinner newAddGoodLabel;
    @BindView(R.id.newAddGood_company)
    Spinner newAddGoodCompany;
    @BindView(R.id.newAddGood_yieldly)
    Spinner newAddGoodYieldly;
    @BindView(R.id.newAddGood_goodsNum)
    EditText newAddGoodGoodsNum;
    @BindView(R.id.newAddGood_moreNum)
    EditText newAddGoodMoreNum;
    @BindView(R.id.newAddGood_lessNum)
    EditText newAddGoodLessNum;
    @BindView(R.id.newAddGood_skuEdit)
    EditText newAddGoodSkuEdit;
    @BindView(R.id.newAddGood_weightValue)
    EditText newAddGoodWeightValue;
    @BindView(R.id.newAddGood_fictiousNum_lin)
    LinearLayout newAddGoodFictiousNumLin;
    @BindView(R.id.newAddGood_fictiousNum)
    EditText newAddGoodFictiousNum;
    @BindView(R.id.newAddGood_goodsOrder)
    EditText newAddGoodGoodsOrder;
    @BindView(R.id.newAddGood_spelling)
    EditText newAddGoodSpelling;
    @BindView(R.id.newAddGood_storeMemStatus)
    Switch newAddGoodStoreMemStatus;
    @BindView(R.id.newAddGood_storeMemPrice)
    EditText newAddGoodStoreMemPrice;
    @BindView(R.id.newAddGood_storeMemIntegral)
    EditText newAddGoodStoreMemIntegral;
    @BindView(R.id.newAddGood_storeMemIntegralLin)
    LinearLayout newAddGoodStoreMemIntegralLin;
    @BindView(R.id.newAddGood_shopMemStatus)
    Switch newAddGoodShopMemStatus;
    @BindView(R.id.newAddGood_shopMemPrice)
    EditText newAddGoodShopMemPrice;
    @BindView(R.id.newAddGood_shopMemIntegral)
    EditText newAddGoodShopMemIntegral;
    @BindView(R.id.newAddGood_shopMemIntegralLin)
    LinearLayout newAddGoodShopMemIntegralLin;
    @BindView(R.id.newAddGood_plusMemStatus)
    Switch newAddGoodPlusMemStatus;
    @BindView(R.id.newAddGood_plusMemPrice)
    EditText newAddGoodPlusMemPrice;
    @BindView(R.id.newAddGood_plusMemIntegral)
    EditText newAddGoodPlusMemIntegral;
    @BindView(R.id.newAddGood_plusMemIntegralLin)
    LinearLayout newAddGoodPlusMemIntegralLin;
    @BindView(R.id.newAddGood_integralStatus)
    Switch newAddGoodIntegralStatus;
    @BindView(R.id.newAddGood_integral)
    EditText newAddGoodIntegral;
    @BindView(R.id.newAddGood_vipRetailState)
    Switch newAddGoodVipRetailState;
    @BindView(R.id.newAddGood_vipOnlineState)
    Switch newAddGoodVipOnlineState;
    @BindView(R.id.newAddGood_guideRoyaltyState)
    Switch newAddGoodGuideRoyaltyState;
    @BindView(R.id.newAddGood_guideRoyaltyCustom)
    Switch newAddGoodGuideRoyaltyCustom;
    @BindView(R.id.newAddGood_guideRoyaltyPrice)
    EditText newAddGoodGuideRoyaltyPrice;
    @BindView(R.id.newAddGood_guideRoyaltyOnlinePrice)
    EditText newAddGoodGuideRoyaltyOnlinePrice;
    @BindView(R.id.newAddGood_commitAndFinish)
    TextView newAddGoodCommitAndFinish;
    @BindView(R.id.newAddGood_commit)
    TextView newAddGoodCommit;
    @BindView(R.id.newAddGood_deliveryView)
    View newAddGoodDeliveryView;
    @BindView(R.id.newAddGood_deliveryLinear)
    LinearLayout newAddGoodDeliveryLinear;
    @BindView(R.id.newAddGood_deliveryAllLinear)
    LinearLayout newAddGoodDeliveryAllLinear;
    @BindView(R.id.newAddGood_saleRuleView1)
    View newAddGoodSaleRuleView1;
    @BindView(R.id.newAddGood_saleRuleLinear1)
    LinearLayout newAddGoodSaleRuleLinear1;
    @BindView(R.id.newAddGood_saleRuleView2)
    View newAddGoodSaleRuleView2;
    @BindView(R.id.newAddGood_saleRuleLinear2)
    LinearLayout newAddGoodSaleRuleLinear2;
    @BindView(R.id.newAddGood_integralView1)
    View newAddGoodIntegralView1;
    @BindView(R.id.newAddGood_integralLinear1)
    LinearLayout newAddGoodIntegralLinear1;
    @BindView(R.id.newAddGood_integralView2)
    View newAddGoodIntegralView2;
    @BindView(R.id.newAddGood_integralLinear2)
    LinearLayout newAddGoodIntegralLinear2;
    @BindView(R.id.newAddGood_guideView)
    View newAddGoodGuideView;
    @BindView(R.id.newAddGood_guideLinear)
    LinearLayout newAddGoodGuideLinear;
    @BindView(R.id.newAddGood_guideView1)
    View newAddGoodGuideView1;
    @BindView(R.id.newAddGood_guideLinear1)
    LinearLayout newAddGoodGuideLinear1;
    @BindView(R.id.newAddGood_guideView2)
    View newAddGoodGuideView2;
    @BindView(R.id.newAddGood_guideLinear2)
    LinearLayout newAddGoodGuideLinear2;
    @BindView(R.id.newAddGood_Q3)
    EditText newAddGoodQ3;
    @BindView(R.id.lin_Q3)
    LinearLayout linQ3;
    @BindView(R.id.price_set)
    LinearLayout price_set;
    @BindView(R.id.lin_purchasePrice)
    LinearLayout linPurchasePrice;
    @BindView(R.id.newAddGood_weightLin)
    LinearLayout newAddGoodWeightLin;
    @BindView(R.id.newAdd_tab)
    TextView newAddTab;
    @BindView(R.id.newAdd_tab1)
    TextView newAddTab1;
    @BindView(R.id.dialog_text)
    RelativeLayout dialogText;
    @BindView(R.id.tint)
    TextView tint;
    @BindView(R.id.newAdd_PLULin)
    LinearLayout newAddPLULin;

    private static ACache aCache;
    private static Context context;
    private LoadingDialog loadingDialog;
    private List<SkuGoodsInfo> skuGoodsList = new ArrayList<>();// 規格信息  數據源

    private CurrencyInfo currencyInfo;
    private static GridImageAdapter mAdapter;
    private static GridImageAdapter mAdapter2;
    private static GridImageAdapter mAdapter3;


    private static JSONArray bannerList=new JSONArray();

    private static String goods_image_id = "";

    private static String goods_img = "";

    private static int imageType = 1;

    private static String video_id = "";

    //商品分類id
    private String classId = "";
    private String goodId = "";

    //配送模板
    private int storeFreightIndex = 0;
    private List<CurrencyInfo.DataBean> storeFreightList = new ArrayList<>();

    //品牌
    private int brandIndex = 0;
    private List<CurrencyInfo.DataBean> brandList = new ArrayList<>();

    //標籤
    private int labelIndex = 0;
    private List<CurrencyInfo.DataBean> labelList = new ArrayList<>();

    //單位
    private int unitIndex = 0;
    private String unitName="";
    private List<CurrencyInfo.DataBean> unitList = new ArrayList<>();

    //產地
    private int yieldlyIndex = 0;
    private List<CurrencyInfo.DataBean> yieldlyList = new ArrayList<>();

    private Intent intent;
    private ChooseTagDialogFragment chooseTagDialogFragment;

    //權限
    private EditSet editSet;

    @Override
    protected void initView() {
        setContentView(R.layout.activity_new_add_good);
        ButterKnife.bind(this);
        context = this;
        aCache = ACache.get(context);

        bannerList=new JSONArray();
        goods_image_id = "";
        goods_img = "";
        imageType = 1;
        video_id = "";

        String str = getIntent().getStringExtra("goodId");
        goodId = str;
        loadingDialog = new LoadingDialog(context);
        if (!TextUtils.isEmpty(goodId)){
            titleTitle.setText("編輯商品");
            newAddGoodQ3.setClickable(false);
            newAddGoodQ3.setFocusable(false);
            newAddGoodGoodsNum.setClickable(false);
            newAddGoodGoodsNum.setFocusable(false);
            newAddGoodPurchasePrice.setClickable(false);
            newAddGoodPurchasePrice.setFocusable(false);
            newAddGoodIsSku.setClickable(false);
            newAddGoodSkuSetting.setVisibility(View.GONE);
//            if (sellcountBean!=null&&!"1".equals(sellcountBean.getJurisdiction().getShowpurch_price())) {
//                newAddGoodPurchasePrice.setVisibility(View.GONE);
//            }else {
//                newAddGoodPurchasePrice.setVisibility(View.VISIBLE);
//            }
        }else {
            titleTitle.setText("添加商品");
        }
        if ("2".equals(aCache.getAsString("platform_type"))){
            linQ3.setVisibility(View.VISIBLE);
        }else {
            linQ3.setVisibility(View.GONE);
        }
        if ("1".equals(aCache.getAsString("userType"))){
            newAddPLULin.setVisibility(View.GONE);
            newAddGoodFictiousNumLin.setVisibility(View.GONE);
            newAddGoodLabelLin.setVisibility(View.GONE);
        }
        initGridImage();
//        setEdit1(newAddGoodPurchasePrice);
//        setEdit1(newAddGoodMoreNum);
//        setEdit1(newAddGoodLessNum);
//        setEdit1(newAddGoodWeightValue);
//        setEditType(newAddGoodMoreNum);
//        setEditType(newAddGoodLessNum);
        if (!TextUtils.isEmpty(goodId)){
            newAddGoodCommit.setVisibility(View.GONE);
        }
        goodInfoSet();
    }


    private void initGridImage(){
        FullyGridLayoutManager fullyGridLayoutManager3 = new FullyGridLayoutManager(this, 1, 1, false);
        newAddGoodCover.setLayoutManager(fullyGridLayoutManager3);
        newAddGoodCover.addItemDecoration(new GridSpacingItemDecoration(1, ScreenUtils.dip2px(this, 0.0F), false));
        mAdapter = new GridImageAdapter(context, () -> {
            PictureSelector.create(NewAddGoodActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、圖片.ofImage()、視頻.ofVideo()、音頻.ofAudio()
                    .imageEngine(GlideEngine.createGlideEngine())// 外部傳入圖片加載引擎，必傳項
                    //.theme(themeId)// 主題樣式設置 具體參考 values/styles   用法：R.style.picture.white.style v2.3.3後 建議使用setPictureStyle()動態方式
//                    .setPictureUIStyle(mSelectorUIStyle)
                    //.setPictureStyle(mPictureParameterStyle)// 動態自定義相冊主題
                    //.setPictureCropStyle(mCropParameterStyle)// 動態自定義裁剪主題
//                    .setPictureWindowAnimationStyle(mWindowAnimationStyle)// 自定義相冊啓動退出動畫
//                    .isWeChatStyle(isWeChatStyle)// 是否開啓微信圖片選擇風格
                    .isUseCustomCamera(false)// 是否使用自定義相機
//                    .setLanguage(language)// 設置語言，默認中文
//                    .isPageStrategy(cbPage.isChecked())// 是否開啓分頁策略 & 每頁多少條；默認開啓
//                    .setRecyclerAnimationMode(animationMode)// 列表動畫效果
                    .isWithVideoImage(true)// 圖片和視頻是否可以同選,只在ofAll模式下有效
                    .isMaxSelectEnabledMask(true)// 選擇數到了最大閥值列表是否啓用蒙層效果
                    //.isAutomaticTitleRecyclerTop(false)// 連續點擊標題欄RecyclerView是否自動回到頂部,默認true
                    //.loadCacheResourcesCallback(GlideCacheEngine.createCacheEngine())// 獲取圖片資源緩存，主要是解決華爲10部分機型在拷貝文件過多時會出現卡的問題，這裏可以判斷只在會出現一直轉圈問題機型上使用
                    //.setOutputCameraPath(createCustomCameraOutPath())// 自定義相機輸出目錄
                    //.setButtonFeatures(CustomCameraView.BUTTON_STATE_BOTH)// 設置自定義相機按鈕狀態
                    .maxSelectNum(1)// 最大圖片選擇數量
                    .minSelectNum(1)// 最小選擇數量
                    .maxVideoSelectNum(1) // 視頻最大選擇數量
                    //.minVideoSelectNum(1)// 視頻最小選擇數量
                    //.closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 關閉在AndroidQ下獲取圖片或視頻寬高相反自動轉換
                    .imageSpanCount(4)// 每行顯示個數
                    .isReturnEmpty(false)// 未選擇數據時點擊按鈕是否可以返回
                    .closeAndroidQChangeWH(true)//如果圖片有旋轉角度則對換寬高,默認爲true
                    .closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 如果視頻有旋轉角度則對換寬高,默認爲false
                    //.isAndroidQTransform(true)// 是否需要處理Android Q 拷貝至應用沙盒的操作，只針對compress(false); && .isEnableCrop(false);有效,默認處理
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 設置相冊Activity方向，不設置默認使用系統
                    .isOriginalImageControl(false)// 是否顯示原圖控制按鈕，如果設置爲true則用戶可以自由選擇是否使用原圖，壓縮、裁剪功能將會失效
                    //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定義視頻播放回調控制，用戶可以使用自己的視頻播放界面
                    //.bindCustomPreviewCallback(new MyCustomPreviewInterfaceListener())// 自定義圖片預覽回調接口
                    //.bindCustomCameraInterfaceListener(new MyCustomCameraInterfaceListener())// 提供給用戶的一些額外的自定義操作回調
                    //.cameraFileName(System.currentTimeMillis() +".jpg")    // 重命名拍照文件名、如果是相冊拍照則內部會自動拼上當前時間戳防止重複，注意這個只在使用相機時可以使用，如果使用相機又開啓了壓縮或裁剪 需要配合壓縮和裁剪文件名api
                    //.renameCompressFile(System.currentTimeMillis() +".jpg")// 重命名壓縮文件名、 如果是多張壓縮則內部會自動拼上當前時間戳防止重複
                    //.renameCropFileName(System.currentTimeMillis() + ".jpg")// 重命名裁剪文件名、 如果是多張裁剪則內部會自動拼上當前時間戳防止重複
                    .selectionMode(PictureConfig.SINGLE)// 多選 or 單選
//                    .isSingleDirectReturn(cb_single_back.isChecked())// 單選模式下是否直接返回，PictureConfig.SINGLE模式下有效
                    .isPreviewImage(true)// 是否可預覽圖片
//                    .isPreviewVideo(cb_preview_video.isChecked())// 是否可預覽視頻
                    //.querySpecifiedFormatSuffix(PictureMimeType.ofJPEG())// 查詢指定後綴格式資源
//                    .isEnablePreviewAudio(cb_preview_audio.isChecked()) // 是否可播放音頻
                    .isCamera(true)// 是否顯示拍照按鈕
                    //.isMultipleSkipCrop(false)// 多圖裁剪時是否支持跳過，默認支持
                    //.isMultipleRecyclerAnimation(false)// 多圖裁剪底部列表顯示動畫效果
                    .isZoomAnim(true)// 圖片列表點擊 縮放效果 默認true
                    //.imageFormat(PictureMimeType.PNG)// 拍照保存圖片格式後綴,默認jpeg,Android Q使用PictureMimeType.PNG_Q
                    .isEnableCrop(false)// 是否裁剪
                    //.basicUCropConfig()//對外提供所有UCropOptions參數配製，但如果PictureSelector原本支持設置的還是會使用原有的設置
                    .isCompress(true)// 是否壓縮
                    //.compressQuality(80)// 圖片壓縮後輸出質量 0~ 100
                    .synOrAsy(false)//同步true或異步false 壓縮 默認同步
                    //.queryMaxFileSize(10)// 只查多少M以內的圖片、視頻、音頻  單位M
                    //.compressSavePath(getPath())//壓縮圖片保存地址
                    //.sizeMultiplier(0.5f)// glide 加載圖片大小 0~1之間 如設置 .glideOverride()無效 注：已廢棄
                    //.glideOverride(160, 160)// glide 加載寬高，越小圖片列表越流暢，但會影響列表圖片瀏覽的清晰度 注：已廢棄
                    .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定義
//                    .hideBottomControls(!cb_hide.isChecked())// 是否顯示uCrop工具欄，默認不顯示
//                    .isGif(cb_isGif.isChecked())// 是否顯示gif圖片
                    //.isWebp(false)// 是否顯示webp圖片,默認顯示
                    //.isBmp(false)//是否顯示bmp圖片,默認顯示
                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圓形裁剪
                    //.setCropDimmedColor(ContextCompat.getColor(getContext(), R.color.app_color_white))// 設置裁剪背景色值
                    //.setCircleDimmedBorderColor(ContextCompat.getColor(getApplicationContext(), R.color.app_color_white))// 設置圓形裁剪邊框色值
                    //.setCircleStrokeWidth(3)// 設置圓形裁剪邊框粗細
                    .showCropFrame(false)// 是否顯示裁剪矩形邊框 圓形裁剪時建議設爲false
                    .showCropGrid(false)// 是否顯示裁剪矩形網格 圓形裁剪時建議設爲false
//                    .isOpenClickSound(cb_voice.isChecked())// 是否開啓點擊聲音
                    .selectionData(mAdapter.getData())// 是否傳入已選圖片
                    //.isDragFrame(false)// 是否可拖動裁剪框(固定)
                    //.videoMinSecond(10)// 查詢多少秒以內的視頻
                    //.videoMaxSecond(15)// 查詢多少秒以內的視頻
                    //.recordVideoSecond(10)//錄製視頻秒數 默認60s
                    //.isPreviewEggs(true)// 預覽圖片時 是否增強左右滑動圖片體驗(圖片滑動一半即可看到上一張是否選中)
                    //.cropCompressQuality(90)// 注：已廢棄 改用cutOutQuality()
//                    .cutOutQuality(90)// 裁剪輸出質量 默認100
                    .minimumCompressSize(100)// 小於多少kb的圖片不壓縮
                    //.cropWH()// 裁剪寬高比，設置如果大於圖片本身寬高則無效
                    //.cropImageWideHigh()// 裁剪寬高比，設置如果大於圖片本身寬高則無效
                    //.rotateEnabled(false) // 裁剪是否可旋轉圖片
                    //.scaleEnabled(false)// 裁剪是否可放大縮小圖片
                    //.videoQuality()// 視頻錄製質量 0 or 1
                    //.forResult(PictureConfig.CHOOSE_REQUEST);//結果回調onActivityResult code
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(List<LocalMedia> result) {
                            goods_image_id="";
                            imageType = 1;
                            for (LocalMedia media : result) {
                                Log.i("TAG", "是否壓縮:" + media.isCompressed());
                                Log.i("TAG", "壓縮:" + media.getCompressPath());
                                Log.i("TAG", "原圖:" + media.getPath());
                                Log.i("TAG", "絕對路徑:" + media.getRealPath());
                                Log.i("TAG", "是否裁剪:" + media.isCut());
                                Log.i("TAG", "裁剪:" + media.getCutPath());
                                Log.i("TAG", "是否開啓原圖:" + media.isOriginal());
                                Log.i("TAG", "原圖路徑:" + media.getOriginalPath());
                                Log.i("TAG", "Android Q 特有Path:" + media.getAndroidQToPath());
                                Log.i("TAG", "寬高: " + media.getWidth() + "x" + media.getHeight());
                                Log.i("TAG", "Size: " + media.getSize());
                                // TODO 可以通過PictureSelectorExternalUtils.getExifInterface();方法獲取一些額外的資源信息，如旋轉角度、經緯度等信息
                            }
                            for (LocalMedia str : result) {
                                String path = "";
                                if (str.isCut() && !str.isCompressed()) {
                                    path = str.getCutPath();
                                } else if (str.isCompressed() || (str.isCut() && str.isCompressed())) {
                                    path = str.getCompressPath();
                                } else {
                                    path = str.getPath();
                                }
                                Log.d("視頻路徑1",path);
                                uploadFile(1, new File(path),result);
                            }
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
        });
        mAdapter.setSelectMax(1);
        newAddGoodCover.setAdapter(mAdapter);
        setAdapterClick(mAdapter);

        FullyGridLayoutManager fullyGridLayoutManager2 = new FullyGridLayoutManager(this, 1, 1, false);
        newAddGoodVideo.setLayoutManager(fullyGridLayoutManager2);
        newAddGoodVideo.addItemDecoration(new GridSpacingItemDecoration(1, ScreenUtils.dip2px(this, 0.0F), false));
        mAdapter2 = new GridImageAdapter(context, () -> {
            PictureSelector.create(NewAddGoodActivity.this)
                    .openGallery(PictureMimeType.ofVideo())// 全部.PictureMimeType.ofAll()、圖片.ofImage()、視頻.ofVideo()、音頻.ofAudio()
                    .imageEngine(GlideEngine.createGlideEngine())// 外部傳入圖片加載引擎，必傳項
                    //.theme(themeId)// 主題樣式設置 具體參考 values/styles   用法：R.style.picture.white.style v2.3.3後 建議使用setPictureStyle()動態方式
//                    .setPictureUIStyle(mSelectorUIStyle)
                    //.setPictureStyle(mPictureParameterStyle)// 動態自定義相冊主題
                    //.setPictureCropStyle(mCropParameterStyle)// 動態自定義裁剪主題
//                    .setPictureWindowAnimationStyle(mWindowAnimationStyle)// 自定義相冊啓動退出動畫
//                    .isWeChatStyle(isWeChatStyle)// 是否開啓微信圖片選擇風格
                    .isUseCustomCamera(false)// 是否使用自定義相機
//                    .setLanguage(language)// 設置語言，默認中文
//                    .isPageStrategy(cbPage.isChecked())// 是否開啓分頁策略 & 每頁多少條；默認開啓
//                    .setRecyclerAnimationMode(animationMode)// 列表動畫效果
//                    .isWithVideoImage(true)// 圖片和視頻是否可以同選,只在ofAll模式下有效
                    .isMaxSelectEnabledMask(true)// 選擇數到了最大閥值列表是否啓用蒙層效果
                    //.isAutomaticTitleRecyclerTop(false)// 連續點擊標題欄RecyclerView是否自動回到頂部,默認true
                    //.loadCacheResourcesCallback(GlideCacheEngine.createCacheEngine())// 獲取圖片資源緩存，主要是解決華爲10部分機型在拷貝文件過多時會出現卡的問題，這裏可以判斷只在會出現一直轉圈問題機型上使用
                    //.setOutputCameraPath(createCustomCameraOutPath())// 自定義相機輸出目錄
                    //.setButtonFeatures(CustomCameraView.BUTTON_STATE_BOTH)// 設置自定義相機按鈕狀態
//                    .maxSelectNum(1)// 最大圖片選擇數量
//                    .minSelectNum(1)// 最小選擇數量
                    .maxVideoSelectNum(1) // 視頻最大選擇數量
                    //.minVideoSelectNum(1)// 視頻最小選擇數量
                    //.closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 關閉在AndroidQ下獲取圖片或視頻寬高相反自動轉換
                    .imageSpanCount(4)// 每行顯示個數
                    .isReturnEmpty(false)// 未選擇數據時點擊按鈕是否可以返回
                    .closeAndroidQChangeWH(true)//如果圖片有旋轉角度則對換寬高,默認爲true
                    .closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 如果視頻有旋轉角度則對換寬高,默認爲false
                    //.isAndroidQTransform(true)// 是否需要處理Android Q 拷貝至應用沙盒的操作，只針對compress(false); && .isEnableCrop(false);有效,默認處理
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 設置相冊Activity方向，不設置默認使用系統
                    .isOriginalImageControl(false)// 是否顯示原圖控制按鈕，如果設置爲true則用戶可以自由選擇是否使用原圖，壓縮、裁剪功能將會失效
                    //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定義視頻播放回調控制，用戶可以使用自己的視頻播放界面
                    //.bindCustomPreviewCallback(new MyCustomPreviewInterfaceListener())// 自定義圖片預覽回調接口
                    //.bindCustomCameraInterfaceListener(new MyCustomCameraInterfaceListener())// 提供給用戶的一些額外的自定義操作回調
                    //.cameraFileName(System.currentTimeMillis() +".jpg")    // 重命名拍照文件名、如果是相冊拍照則內部會自動拼上當前時間戳防止重複，注意這個只在使用相機時可以使用，如果使用相機又開啓了壓縮或裁剪 需要配合壓縮和裁剪文件名api
                    //.renameCompressFile(System.currentTimeMillis() +".jpg")// 重命名壓縮文件名、 如果是多張壓縮則內部會自動拼上當前時間戳防止重複
                    //.renameCropFileName(System.currentTimeMillis() + ".jpg")// 重命名裁剪文件名、 如果是多張裁剪則內部會自動拼上當前時間戳防止重複
                    .selectionMode(PictureConfig.SINGLE)// 多選 or 單選
//                    .isSingleDirectReturn(cb_single_back.isChecked())// 單選模式下是否直接返回，PictureConfig.SINGLE模式下有效
//                    .isPreviewImage(true)// 是否可預覽圖片
                    .isPreviewVideo(true)// 是否可預覽視頻
                    //.querySpecifiedFormatSuffix(PictureMimeType.ofJPEG())// 查詢指定後綴格式資源
//                    .isEnablePreviewAudio(cb_preview_audio.isChecked()) // 是否可播放音頻
                    .isCamera(true)// 是否顯示拍照按鈕
                    //.isMultipleSkipCrop(false)// 多圖裁剪時是否支持跳過，默認支持
                    //.isMultipleRecyclerAnimation(false)// 多圖裁剪底部列表顯示動畫效果
                    .isZoomAnim(true)// 圖片列表點擊 縮放效果 默認true
                    //.imageFormat(PictureMimeType.PNG)// 拍照保存圖片格式後綴,默認jpeg,Android Q使用PictureMimeType.PNG_Q
                    .isEnableCrop(true)// 是否裁剪
                    //.basicUCropConfig()//對外提供所有UCropOptions參數配製，但如果PictureSelector原本支持設置的還是會使用原有的設置
                    .isCompress(true)// 是否壓縮
                    //.compressQuality(80)// 圖片壓縮後輸出質量 0~ 100
                    .synOrAsy(false)//同步true或異步false 壓縮 默認同步
                    //.queryMaxFileSize(10)// 只查多少M以內的圖片、視頻、音頻  單位M
                    //.compressSavePath(getPath())//壓縮圖片保存地址
                    //.sizeMultiplier(0.5f)// glide 加載圖片大小 0~1之間 如設置 .glideOverride()無效 注：已廢棄
                    //.glideOverride(160, 160)// glide 加載寬高，越小圖片列表越流暢，但會影響列表圖片瀏覽的清晰度 注：已廢棄
                    .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定義
//                    .hideBottomControls(!cb_hide.isChecked())// 是否顯示uCrop工具欄，默認不顯示
//                    .isGif(cb_isGif.isChecked())// 是否顯示gif圖片
                    //.isWebp(false)// 是否顯示webp圖片,默認顯示
                    //.isBmp(false)//是否顯示bmp圖片,默認顯示
                    .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圓形裁剪
                    //.setCropDimmedColor(ContextCompat.getColor(getContext(), R.color.app_color_white))// 設置裁剪背景色值
                    //.setCircleDimmedBorderColor(ContextCompat.getColor(getApplicationContext(), R.color.app_color_white))// 設置圓形裁剪邊框色值
                    //.setCircleStrokeWidth(3)// 設置圓形裁剪邊框粗細
                    .showCropFrame(true)// 是否顯示裁剪矩形邊框 圓形裁剪時建議設爲false
                    .showCropGrid(true)// 是否顯示裁剪矩形網格 圓形裁剪時建議設爲false
//                    .isOpenClickSound(cb_voice.isChecked())// 是否開啓點擊聲音
                    .selectionData(mAdapter2.getData())// 是否傳入已選圖片
                    //.isDragFrame(false)// 是否可拖動裁剪框(固定)
                    //.videoMinSecond(10)// 查詢多少秒以內的視頻
                    //.videoMaxSecond(15)// 查詢多少秒以內的視頻
                    //.recordVideoSecond(10)//錄製視頻秒數 默認60s
                    //.isPreviewEggs(true)// 預覽圖片時 是否增強左右滑動圖片體驗(圖片滑動一半即可看到上一張是否選中)
                    //.cropCompressQuality(90)// 注：已廢棄 改用cutOutQuality()
                    .cutOutQuality(90)// 裁剪輸出質量 默認100
                    .minimumCompressSize(100)// 小於多少kb的圖片不壓縮
                    //.cropWH()// 裁剪寬高比，設置如果大於圖片本身寬高則無效
                    //.cropImageWideHigh()// 裁剪寬高比，設置如果大於圖片本身寬高則無效
                    //.rotateEnabled(false) // 裁剪是否可旋轉圖片
                    //.scaleEnabled(false)// 裁剪是否可放大縮小圖片
                    //.videoQuality()// 視頻錄製質量 0 or 1
                    //.forResult(PictureConfig.CHOOSE_REQUEST);//結果回調onActivityResult code
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(List<LocalMedia> result) {
                            imageType = 2;
                            video_id="";
                            for (LocalMedia media : result) {
                                Log.i("TAG", "是否壓縮:" + media.isCompressed());
                                Log.i("TAG", "壓縮:" + media.getCompressPath());
                                Log.i("TAG", "原圖:" + media.getPath());
                                Log.i("TAG", "絕對路徑:" + media.getRealPath());
                                Log.i("TAG", "是否裁剪:" + media.isCut());
                                Log.i("TAG", "裁剪:" + media.getCutPath());
                                Log.i("TAG", "是否開啓原圖:" + media.isOriginal());
                                Log.i("TAG", "原圖路徑:" + media.getOriginalPath());
                                Log.i("TAG", "Android Q 特有Path:" + media.getAndroidQToPath());
                                Log.i("TAG", "寬高: " + media.getWidth() + "x" + media.getHeight());
                                Log.i("TAG", "Size: " + media.getSize());
                                // TODO 可以通過PictureSelectorExternalUtils.getExifInterface();方法獲取一些額外的資源信息，如旋轉角度、經緯度等信息
                            }
                            for (LocalMedia str : result) {
                                String path = "";
                                path=str.getRealPath();
//                                if (str.isCut() && !str.isCompressed()) {
//                                    path = str.getCutPath();
//                                } else if (str.isCompressed() || (str.isCut() && str.isCompressed())) {
//                                    path = str.getCompressPath();
//                                } else {
//                                    path = str.getPath();
//                                }
                                compressVideo(context,path,result);
//                                double fileSize=FileSize.getFileOrFilesSize(path,3);
//                                if (fileSize>10){
//                                    Toast.makeText(context,"文件大小不符",Toast.LENGTH_SHORT).show();
//                                }else {
//                                    uploadFile(2, new File(path),result);
//                                }
                            }
//                            mAdapter2.setList(result);
//                            mAdapter2.notifyDataSetChanged();
                        }

                        @Override
                        public void onCancel() {
                        }
                    });
        });
        mAdapter2.setSelectMax(1);
        newAddGoodVideo.setAdapter(mAdapter2);
        setAdapterClick(mAdapter2);

//        FullyGridLayoutManager fullyGridLayoutManager1 = new FullyGridLayoutManager(this, 4, GridLayoutManager.HORIZONTAL, false);
        newAddGoodBanner.setLayoutManager(new GridLayoutManager(this,4));
        newAddGoodBanner.addItemDecoration(new GridSpacingItemDecoration(4, ScreenUtils.dip2px(this, 8.0F), false));
        mAdapter3 = new GridImageAdapter(context, () -> {
            PictureSelector.create(NewAddGoodActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、圖片.ofImage()、視頻.ofVideo()、音頻.ofAudio()
                    .imageEngine(GlideEngine.createGlideEngine())// 外部傳入圖片加載引擎，必傳項
                    //.theme(themeId)// 主題樣式設置 具體參考 values/styles   用法：R.style.picture.white.style v2.3.3後 建議使用setPictureStyle()動態方式
//                    .setPictureUIStyle(mSelectorUIStyle)
                    //.setPictureStyle(mPictureParameterStyle)// 動態自定義相冊主題
                    //.setPictureCropStyle(mCropParameterStyle)// 動態自定義裁剪主題
//                    .setPictureWindowAnimationStyle(mWindowAnimationStyle)// 自定義相冊啓動退出動畫
//                    .isWeChatStyle(isWeChatStyle)// 是否開啓微信圖片選擇風格
                    .isUseCustomCamera(false)// 是否使用自定義相機
//                    .setLanguage(language)// 設置語言，默認中文
//                    .isPageStrategy(cbPage.isChecked())// 是否開啓分頁策略 & 每頁多少條；默認開啓
//                    .setRecyclerAnimationMode(animationMode)// 列表動畫效果
                    .isWithVideoImage(true)// 圖片和視頻是否可以同選,只在ofAll模式下有效
                    .isMaxSelectEnabledMask(true)// 選擇數到了最大閥值列表是否啓用蒙層效果
                    //.isAutomaticTitleRecyclerTop(false)// 連續點擊標題欄RecyclerView是否自動回到頂部,默認true
                    //.loadCacheResourcesCallback(GlideCacheEngine.createCacheEngine())// 獲取圖片資源緩存，主要是解決華爲10部分機型在拷貝文件過多時會出現卡的問題，這裏可以判斷只在會出現一直轉圈問題機型上使用
                    //.setOutputCameraPath(createCustomCameraOutPath())// 自定義相機輸出目錄
                    //.setButtonFeatures(CustomCameraView.BUTTON_STATE_BOTH)// 設置自定義相機按鈕狀態
                    .maxSelectNum(15)// 最大圖片選擇數量
                    .minSelectNum(1)// 最小選擇數量
                    .maxVideoSelectNum(1) // 視頻最大選擇數量
                    //.minVideoSelectNum(1)// 視頻最小選擇數量
                    //.closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 關閉在AndroidQ下獲取圖片或視頻寬高相反自動轉換
                    .imageSpanCount(4)// 每行顯示個數
                    .isReturnEmpty(false)// 未選擇數據時點擊按鈕是否可以返回
                    .closeAndroidQChangeWH(true)//如果圖片有旋轉角度則對換寬高,默認爲true
                    .closeAndroidQChangeVideoWH(!SdkVersionUtils.checkedAndroid_Q())// 如果視頻有旋轉角度則對換寬高,默認爲false
                    //.isAndroidQTransform(true)// 是否需要處理Android Q 拷貝至應用沙盒的操作，只針對compress(false); && .isEnableCrop(false);有效,默認處理
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 設置相冊Activity方向，不設置默認使用系統
                    .isOriginalImageControl(false)// 是否顯示原圖控制按鈕，如果設置爲true則用戶可以自由選擇是否使用原圖，壓縮、裁剪功能將會失效
                    //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定義視頻播放回調控制，用戶可以使用自己的視頻播放界面
                    //.bindCustomPreviewCallback(new MyCustomPreviewInterfaceListener())// 自定義圖片預覽回調接口
                    //.bindCustomCameraInterfaceListener(new MyCustomCameraInterfaceListener())// 提供給用戶的一些額外的自定義操作回調
                    //.cameraFileName(System.currentTimeMillis() +".jpg")    // 重命名拍照文件名、如果是相冊拍照則內部會自動拼上當前時間戳防止重複，注意這個只在使用相機時可以使用，如果使用相機又開啓了壓縮或裁剪 需要配合壓縮和裁剪文件名api
                    //.renameCompressFile(System.currentTimeMillis() +".jpg")// 重命名壓縮文件名、 如果是多張壓縮則內部會自動拼上當前時間戳防止重複
                    //.renameCropFileName(System.currentTimeMillis() + ".jpg")// 重命名裁剪文件名、 如果是多張裁剪則內部會自動拼上當前時間戳防止重複
                    .selectionMode(PictureConfig.MULTIPLE)// 多選 or 單選
//                    .isSingleDirectReturn(cb_single_back.isChecked())// 單選模式下是否直接返回，PictureConfig.SINGLE模式下有效
                    .isPreviewImage(true)// 是否可預覽圖片
//                    .isPreviewVideo(cb_preview_video.isChecked())// 是否可預覽視頻
                    //.querySpecifiedFormatSuffix(PictureMimeType.ofJPEG())// 查詢指定後綴格式資源
//                    .isEnablePreviewAudio(cb_preview_audio.isChecked()) // 是否可播放音頻
                    .isCamera(true)// 是否顯示拍照按鈕
                    //.isMultipleSkipCrop(false)// 多圖裁剪時是否支持跳過，默認支持
                    //.isMultipleRecyclerAnimation(false)// 多圖裁剪底部列表顯示動畫效果
                    .isZoomAnim(true)// 圖片列表點擊 縮放效果 默認true
                    //.imageFormat(PictureMimeType.PNG)// 拍照保存圖片格式後綴,默認jpeg,Android Q使用PictureMimeType.PNG_Q
                    .isEnableCrop(false)// 是否裁剪
                    //.basicUCropConfig()//對外提供所有UCropOptions參數配製，但如果PictureSelector原本支持設置的還是會使用原有的設置
                    .isCompress(true)// 是否壓縮
                    //.compressQuality(80)// 圖片壓縮後輸出質量 0~ 100
                    .synOrAsy(false)//同步true或異步false 壓縮 默認同步
                    //.queryMaxFileSize(10)// 只查多少M以內的圖片、視頻、音頻  單位M
                    //.compressSavePath(getPath())//壓縮圖片保存地址
                    //.sizeMultiplier(0.5f)// glide 加載圖片大小 0~1之間 如設置 .glideOverride()無效 注：已廢棄
                    //.glideOverride(160, 160)// glide 加載寬高，越小圖片列表越流暢，但會影響列表圖片瀏覽的清晰度 注：已廢棄
                    .withAspectRatio(1, 1)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定義
//                    .hideBottomControls(!cb_hide.isChecked())// 是否顯示uCrop工具欄，默認不顯示
//                    .isGif(cb_isGif.isChecked())// 是否顯示gif圖片
                    //.isWebp(false)// 是否顯示webp圖片,默認顯示
                    //.isBmp(false)//是否顯示bmp圖片,默認顯示
                    .freeStyleCropEnabled(false)// 裁剪框是否可拖拽
                    .circleDimmedLayer(false)// 是否圓形裁剪
                    //.setCropDimmedColor(ContextCompat.getColor(getContext(), R.color.app_color_white))// 設置裁剪背景色值
                    //.setCircleDimmedBorderColor(ContextCompat.getColor(getApplicationContext(), R.color.app_color_white))// 設置圓形裁剪邊框色值
                    //.setCircleStrokeWidth(3)// 設置圓形裁剪邊框粗細
                    .showCropFrame(false)// 是否顯示裁剪矩形邊框 圓形裁剪時建議設爲false
                    .showCropGrid(false)// 是否顯示裁剪矩形網格 圓形裁剪時建議設爲false
//                    .isOpenClickSound(cb_voice.isChecked())// 是否開啓點擊聲音
                    .selectionData(mAdapter3.getData())// 是否傳入已選圖片
                    //.isDragFrame(false)// 是否可拖動裁剪框(固定)
                    //.videoMinSecond(10)// 查詢多少秒以內的視頻
                    //.videoMaxSecond(15)// 查詢多少秒以內的視頻
                    //.recordVideoSecond(10)//錄製視頻秒數 默認60s
                    //.isPreviewEggs(true)// 預覽圖片時 是否增強左右滑動圖片體驗(圖片滑動一半即可看到上一張是否選中)
                    //.cropCompressQuality(90)// 注：已廢棄 改用cutOutQuality()
                    .cutOutQuality(90)// 裁剪輸出質量 默認100
                    .minimumCompressSize(100)// 小於多少kb的圖片不壓縮
                    //.cropWH()// 裁剪寬高比，設置如果大於圖片本身寬高則無效
                    //.cropImageWideHigh()// 裁剪寬高比，設置如果大於圖片本身寬高則無效
                    //.rotateEnabled(false) // 裁剪是否可旋轉圖片
                    //.scaleEnabled(false)// 裁剪是否可放大縮小圖片
                    //.videoQuality()// 視頻錄製質量 0 or 1
                    //.forResult(PictureConfig.CHOOSE_REQUEST);//結果回調onActivityResult code
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(List<LocalMedia> result) {
                            imageType = 3;
                            bannerList=new JSONArray();
                            for (LocalMedia media : result) {
                                Log.i("TAG", "是否壓縮:" + media.isCompressed());
                                Log.i("TAG", "壓縮:" + media.getCompressPath());
                                Log.i("TAG", "原圖:" + media.getPath());
                                Log.i("TAG", "絕對路徑:" + media.getRealPath());
                                Log.i("TAG", "是否裁剪:" + media.isCut());
                                Log.i("TAG", "裁剪:" + media.getCutPath());
                                Log.i("TAG", "是否開啓原圖:" + media.isOriginal());
                                Log.i("TAG", "原圖路徑:" + media.getOriginalPath());
                                Log.i("TAG", "Android Q 特有Path:" + media.getAndroidQToPath());
                                Log.i("TAG", "寬高: " + media.getWidth() + "x" + media.getHeight());
                                Log.i("TAG", "Size: " + media.getSize());
                                // TODO 可以通過PictureSelectorExternalUtils.getExifInterface();方法獲取一些額外的資源信息，如旋轉角度、經緯度等信息
                            }
                            for (LocalMedia str : result) {
                                String path = "";
                                if (str.isCut() && !str.isCompressed()) {
                                    path = str.getCutPath();
                                } else if (str.isCompressed() || (str.isCut() && str.isCompressed())) {
                                    path = str.getCompressPath();
                                } else {
                                    path = str.getPath();
                                }
                                uploadFile(1, new File(path),result);
                            }
//                            mAdapter3.setList(result);
//                            mAdapter3.notifyDataSetChanged();
                        }

                        @Override
                        public void onCancel() {

                        }
                    });
        });
        mAdapter3.setSelectMax(15);
        newAddGoodBanner.setAdapter(mAdapter3);
        setAdapterClick(mAdapter3);
    }

    String newVideoPath="";
    private void compressVideo(Context mContext, final String videoPath,List<LocalMedia> result) {
        dialogText.setVisibility(View.VISIBLE);
        Message message=new Message();
        message.what=5;
        message.obj="影片壓縮中";
        handler.sendMessage(message);
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    newVideoPath = with(mContext).compressVideo(videoPath, Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath());
                    double fileSize=FileSize.getFileOrFilesSize(newVideoPath,3);
                    if (fileSize>10){
                        Message message=new Message();
                        message.what=5;
                        message.obj="上傳文件大小不符！";
                        handler.sendMessage(message);
                    }else {
                        Message message=new Message();
                        message.what=4;
                        message.obj=result;
                        handler.sendMessage(message);
                    }
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }



    private void initLayout(int goods_integral_state) {
        if ("2".equals(aCache.getAsString("userType"))||"3".equals(aCache.getAsString("userType"))) {
            newAddGoodDeliveryAllLinear.setVisibility(View.VISIBLE);
            newAddGoodSaleRuleView1.setVisibility(View.VISIBLE);
            newAddGoodSaleRuleLinear1.setVisibility(View.VISIBLE);
            newAddGoodSaleRuleView2.setVisibility(View.VISIBLE);
            newAddGoodSaleRuleLinear2.setVisibility(View.VISIBLE);

//            if ("1".equals(aCache.getAsString("goods_integral_state"))) {
            if (goods_integral_state==1) {
                newAddGoodIntegralView1.setVisibility(View.VISIBLE);
                newAddGoodIntegralLinear1.setVisibility(View.VISIBLE);
                newAddGoodIntegralView2.setVisibility(View.VISIBLE);
                newAddGoodIntegralLinear2.setVisibility(View.VISIBLE);
            } else {
                newAddGoodIntegralView1.setVisibility(View.GONE);
                newAddGoodIntegralLinear1.setVisibility(View.GONE);
                newAddGoodIntegralView2.setVisibility(View.GONE);
                newAddGoodIntegralLinear2.setVisibility(View.GONE);
            }

            newAddGoodGuideView.setVisibility(View.VISIBLE);
            newAddGoodGuideLinear.setVisibility(View.VISIBLE);

        } else {
            newAddGoodDeliveryAllLinear.setVisibility(View.GONE);
            newAddGoodSaleRuleView1.setVisibility(View.GONE);
            newAddGoodSaleRuleLinear1.setVisibility(View.GONE);
            newAddGoodSaleRuleView2.setVisibility(View.GONE);
            newAddGoodSaleRuleLinear2.setVisibility(View.GONE);

            newAddGoodIntegralView1.setVisibility(View.GONE);
            newAddGoodIntegralLinear1.setVisibility(View.GONE);
            newAddGoodIntegralView2.setVisibility(View.GONE);
            newAddGoodIntegralLinear2.setVisibility(View.GONE);

            newAddGoodGuideView.setVisibility(View.GONE);
            newAddGoodGuideLinear.setVisibility(View.GONE);
        }
    }

//    private void setEditType(EditText newAddGoodMoreNum) {
//        newAddGoodMoreNum.setKeyListener(new NumberKeyListener() {
//            @NonNull
//            @Override
//            protected char[] getAcceptedChars() {
//                char[] numberChars = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
//                return numberChars;
//            }
//
//            @Override
//            public int getInputType() {
//                return 0;
//            }
//        });
//    }

    private NewGoodInfo.DataBean newGoodInfo=null;

    @Override
    protected void initData() {
        if (!TextUtils.isEmpty(goodId)) {
            NewGoodInfo.DataBean dataBean = (NewGoodInfo.DataBean) getIntent().getSerializableExtra("info");
            newGoodInfo = dataBean;
            if (dataBean != null) {
                NewGoodInfo.DataBean.GoodsBean goodsBean = dataBean.getGoods();
                newAddGoodName.setText(goodsBean.getGoods_name());
                newAddGoodFreightNumber.setText(goodsBean.getGoods_number());
                newAddGoodCode.setText(goodsBean.getGoods_code());
                classId = goodsBean.getGoods_class_id();
//                String str1 = "";
//                for (String goodsClassBean : newGoodInfo.getGoods_class()) {
//                    StringBuilder stringBuilder1 = new StringBuilder();
//                    stringBuilder1.append(str1);
//                    stringBuilder1.append(goodsClassBean.getClass_name());
//                    stringBuilder1.append("/");
//                    str1 = stringBuilder1.toString();
//                }
//                String str2 = str1;
//                if (!TextUtils.isEmpty(str1))
//                    str2 = str1.substring(0, str1.length() - 1);
                newAddGoodClassificationName.setText(getIntent().getStringExtra("className"));
                EditText editText2 = newAddGoodRetailPrice;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getRetail_price());
                stringBuilder.append("");
                editText2.setText(stringBuilder.toString());
                editText2 = newAddGoodShopPrice;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getOnline_price());
                stringBuilder.append("");
                editText2.setText(stringBuilder.toString());
                if (!TextUtils.isEmpty(goodsBean.getGoods_img())) {
                    ArrayList arrayList1 = new ArrayList();
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPath(goodsBean.getGoods_img());
                    arrayList1.add(localMedia);
                    goods_image_id=goodsBean.getGoods_img_id();
                    mAdapter.setList(arrayList1);
                    mAdapter.notifyDataSetChanged();
                }
                if (!TextUtils.isEmpty(goodsBean.getGoods_video())) {
                    ArrayList arrayList1 = new ArrayList();
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPath(goodsBean.getGoods_video());
                    video_id=goodsBean.getVideo_id();
                    arrayList1.add(localMedia);
                    mAdapter2.setList(arrayList1);
                    mAdapter2.notifyDataSetChanged();
                }
                ArrayList arrayList = new ArrayList();
                for (NewGoodInfo.DataBean.BannerListBean bannerListBean : newGoodInfo.getBannerList()) {
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPath(bannerListBean.getImage());
                    arrayList.add(localMedia);
                }
                mAdapter3.setList(arrayList);
                mAdapter3.notifyDataSetChanged();
                newAddGoodPluIndex.setText(goodsBean.getPlu_code());
                newAddGoodIsWeight.setChecked("2".equals(goodsBean.getPricing_method()));
                newAddGoodIsSerial.setChecked("1".equals(goodsBean.getSerial_number_state()));
                newAddGoodIsSerial.setClickable(false);
                newAddGoodIsSerial.setFocusable(false);
                if ("1".equals(goodsBean.getSerial_number_state())){
                    newAddGoodGoodsNum.setClickable(false);
                    newAddGoodGoodsNum.setFocusable(false);
                    newAddGoodIsWeight.setClickable(false);
                    newAddGoodIsWeight.setFocusable(false);
                    newAddGoodSplitState.setClickable(false);
                    newAddGoodSplitState.setFocusable(false);
//                    newAddGoodIsWeight.setChecked(false);
//                    newAddGoodSplitState.setChecked(false);
                }
                for (Integer integer : goodsBean.getDelivery_type()) {
                    switch (integer) {
                        case 1:
                            newAddGoodDelivery1.setChecked(true);
                            break;
                        case 2:
                            newAddGoodDelivery2.setChecked(true);
                            break;
                        case 3:
                            newAddGoodDelivery3.setChecked(true);
                            newAddGoodDeliveryLinear.setVisibility(View.VISIBLE);
                            break;
                    }
                }
                newAddGoodStatus.setChecked("0".equals(goodsBean.getStatus()));
                newAddGoodRetailState.setChecked("1".equals(goodsBean.getRetail_state()));
                if ("1".equals(goodsBean.getRetail_state())){
                    newAddTab.setVisibility(View.VISIBLE);
                }else{
                    newAddTab.setVisibility(View.GONE);
                }
                newAddGoodOnlineState.setChecked("1".equals(goodsBean.getOnline_state()));
                if ("1".equals(goodsBean.getOnline_state())){
                    if ("2".equals(aCache.getAsString("userType"))||"3".equals(aCache.getAsString("userType"))) {
                        newAddGoodAdvanceSaleStatus.setVisibility(View.VISIBLE);
                    } else {
                        newAddGoodAdvanceSaleStatus.setChecked(false);
                        newAddGoodAdvanceSaleStatus.setVisibility(View.GONE);
                    }
//                    newAddGoodAdvanceSaleStatus.setVisibility(View.VISIBLE);
                    newAddTab1.setVisibility(View.VISIBLE);
                }
                newAddGoodAdvanceSaleStatus.setChecked("1".equals(goodsBean.getAdvance_sale_status()));
                newAddGoodSplitState.setChecked("1".equals(goodsBean.getSplit_state()));
                newAddGoodRefundState.setChecked("1".equals(goodsBean.getRefund_state()));
                newAddGoodExchangeState.setChecked("1".equals(goodsBean.getExchange_state()));
                newAddGoodSubheading.setText(goodsBean.getSubheading());
                newAddGoodPurchasePrice.setText(goodsBean.getPurchase_price());
                EditText editText1 = newAddGoodGoodsNum;
                stringBuilder = new StringBuilder();
                stringBuilder.append("0".equals(goodsBean.getGoods_num())?"":goodsBean.getGoods_num());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                if (!"0".equals(goodsBean.getGoods_num())&&goodsBean.getGoods_num().contains(".")){
                    newAddGoodIsWeight.setClickable(false);
                    newAddGoodIsWeight.setFocusable(false);
                }
                editText1 = newAddGoodMoreNum;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getMore_num());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                editText1 = newAddGoodLessNum;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getLess_num());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                newAddGoodSkuEdit.setText(goodsBean.getSpecifications());
                editText1 = newAddGoodWeightValue;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getWeight_value());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                newAddGoodFictiousNum.setText(goodsBean.getFictitious_num());
                newAddGoodGoodsOrder.setText(goodsBean.getGoods_order());
                newAddGoodSpelling.setText(goodsBean.getSimple_spelling());
                newAddGoodStoreMemStatus.setChecked("1".equals(goodsBean.getStore_mem_status()));
                editText1 = newAddGoodStoreMemPrice;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getStore_mem_price());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                newAddGoodStoreMemIntegral.setText(goodsBean.getStore_mem_integral());
                newAddGoodShopMemStatus.setChecked("1".equals(goodsBean.getShop_mem_status()));
                editText1 = newAddGoodShopMemPrice;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getShop_mem_price());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                newAddGoodShopMemIntegral.setText(goodsBean.getShop_mem_integral());
                newAddGoodPlusMemStatus.setChecked("1".equals(goodsBean.getPlus_mem_status()));
                editText1 = newAddGoodPlusMemPrice;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getPlus_price());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                newAddGoodIntegralStatus.setChecked("1".equals(goodsBean.getIntegral_mem_status()));
                editText1 = newAddGoodIntegral;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getIntegral());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                newAddGoodPlusMemIntegral.setText(goodsBean.getPlus_mem_integral());
                newAddGoodVipRetailState.setChecked("1".equals(goodsBean.getVip_retail_state()));
                newAddGoodVipOnlineState.setChecked("1".equals(goodsBean.getVip_online_state()));
                newAddGoodGuideRoyaltyState.setChecked("1".equals(goodsBean.getGuide_royalty_state()));
                newAddGoodGuideRoyaltyCustom.setChecked("1".equals(goodsBean.getGuide_royalty_custom_state()));
                if ("1".equals(goodsBean.getGuide_royalty_custom_state())){
                    newAddGoodGuideLinear1.setVisibility(View.VISIBLE);
                    newAddGoodGuideLinear2.setVisibility(View.VISIBLE);
                    if (skuGoodsAdapter!=null)
                        skuGoodsAdapter.setGuide(true);
                    setSkuGoodsAdapter();
                }
                editText1 = newAddGoodGuideRoyaltyPrice;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getGuide_royalty_price());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                editText1 = newAddGoodGuideRoyaltyOnlinePrice;
                stringBuilder = new StringBuilder();
                stringBuilder.append(goodsBean.getGuide_royalty_online_price());
                stringBuilder.append("");
                editText1.setText(stringBuilder.toString());
                newAddGoodQ3.setText(goodsBean.getThird_goods_code());
                newAddGoodIsSku.setChecked("2".equals(goodsBean.getAttribute_state()));
                if ("2".equals(goodsBean.getAttribute_state())){
                    goodInfoSku(goodsBean.getId());
                    if (skuGoodsAdapter!=null){
                        skuGoodsAdapter.setmStatus(newAddGoodShopMemStatus.isChecked(),
                                newAddGoodStoreMemStatus.isChecked(),newAddGoodPlusMemStatus.isChecked());
                        skuGoodsAdapter.setIsSerial(newAddGoodIsSerial.isChecked());
                        skuGoodsAdapter.setIsWeight(newAddGoodIsWeight.isChecked());
                        newAddGoodSkuGoodsListView.setAdapter(skuGoodsAdapter);
                        skuGoodsAdapter.setGuide(newAddGoodGuideRoyaltyCustom.isChecked());
                    }
                    setSkuGoodsAdapter();

                    newAddGoodIsWeight.setFocusable(false);
                    newAddGoodIsWeight.setClickable(false);
                }
            }
        }
        getStoreFreightTem();
        getSelectBrand();
        getGoodsLabelList();
        if (newAddGoodIsWeight.isChecked()){
            newAddGoodGoodsNum.setInputType(8194);
            newAddGoodMoreNum.setInputType(8194);
            newAddGoodLessNum.setInputType(8194);
            unitList.clear();
            unitList.add(new CurrencyInfo.DataBean("0", "請選擇單位", "請選擇單位", "請選擇單位"));
            unitList.add(new CurrencyInfo.DataBean("0", "kg", "kg", "kg"));
            unitList.add(new CurrencyInfo.DataBean("0", "KG", "KG", "KG"));
            unitList.add(new CurrencyInfo.DataBean("0", "斤", "斤", "斤"));
            unitList.add(new CurrencyInfo.DataBean("0", "公斤", "公斤", "公斤"));
            unitList.add(new CurrencyInfo.DataBean("0", "千克", "千克", "千克"));
            unitList.add(new CurrencyInfo.DataBean("0", "g", "g", "g"));
            unitList.add(new CurrencyInfo.DataBean("0", "G", "G", "G"));
            unitList.add(new CurrencyInfo.DataBean("0", "克", "克", "克"));
            ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, unitList) {
                @Override
                public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                    @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                    final TextView text = view.findViewById(R.id.drop_view);
                    text.setText(unitList.get(position).getName());
                    unitName=unitList.get(position).getName();
                    return view;
                }

                @NonNull
                @Override
                public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                    View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                    final TextView text = view.findViewById(R.id.spinner_tv);
                    text.setText(unitList.get(position).getName());
                    unitName=unitList.get(position).getName();
                    return view;
                }
            };
            newAddGoodCompany.setAdapter(arrayAdapter);
            if (newGoodInfo!=null) {
                if (!TextUtils.isEmpty(newGoodInfo.getGoods().getCompany())) {
                    for (int i = 0; i < unitList.size(); i++) {
                        if (unitList.get(i).getName().equals(newGoodInfo.getGoods().getCompany())) {
                            newAddGoodCompany.setSelection(i);
                            unitIndex = i;
                            unitName = unitList.get(i).getName();
                            Message message=new Message();
                            message.what=2;
                            message.obj=unitList.get(i).getName();
                            handler.sendMessage(message);
                        }
                    }
                }
            }
        }else {
            newAddGoodGoodsNum.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
            newAddGoodMoreNum.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
            newAddGoodLessNum.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
            getUnitSelect();
        }
        getGoodsYieldlyList();
    }

    @Override
    protected void initListener() {
        setTextListener2(newAddGoodGoodsNum);
        setTextListener2(newAddGoodWeightValue);
        setTextListener2(newAddGoodMoreNum);
        setTextListener2(newAddGoodLessNum);
        setTextListener1(newAddGoodGuideRoyaltyOnlinePrice);
        setTextListener1(newAddGoodGuideRoyaltyPrice);
        setTextListener1(newAddGoodPlusMemPrice);
        setTextListener1(newAddGoodPurchasePrice);
        setTextListener1(newAddGoodRetailPrice);
        setTextListener1(newAddGoodShopMemPrice);
        setTextListener1(newAddGoodShopPrice);
        setTextListener1(newAddGoodStoreMemPrice);
        newAddGoodDeliveryTemplate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                storeFreightIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        newAddGoodBrand.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                brandIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        newAddGoodLabel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                labelIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        newAddGoodCompany.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                unitIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        newAddGoodYieldly.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                yieldlyIndex = position;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        newAddGoodIsWeight.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (skuGoodsAdapter!=null){
                skuGoodsAdapter.setIsWeight(isChecked);
            }
            setSkuGoodsAdapter();
            if (isChecked) {
                newAddGoodGoodsNum.setInputType (8194);
                newAddGoodMoreNum.setInputType(8194);
                newAddGoodLessNum.setInputType(8194);
                newAddGoodWeightLin.setVisibility(View.GONE);
                unitList.clear();
                unitList.add(new CurrencyInfo.DataBean("0", "請選擇單位", "請選擇單位", "請選擇單位"));
                unitList.add(new CurrencyInfo.DataBean("0", "kg", "kg", "kg"));
                unitList.add(new CurrencyInfo.DataBean("0", "KG", "KG", "KG"));
                unitList.add(new CurrencyInfo.DataBean("0", "斤", "斤", "斤"));
                unitList.add(new CurrencyInfo.DataBean("0", "公斤", "公斤", "公斤"));
                unitList.add(new CurrencyInfo.DataBean("0", "千克", "千克", "千克"));
                unitList.add(new CurrencyInfo.DataBean("0", "g", "g", "g"));
                unitList.add(new CurrencyInfo.DataBean("0", "G", "G", "G"));
                unitList.add(new CurrencyInfo.DataBean("0", "克", "克", "克"));
                ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, unitList) {
                    @Override
                    public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                        @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                        final TextView text = view.findViewById(R.id.drop_view);
                        text.setText(unitList.get(position).getName());
                        unitName=unitList.get(position).getName();
                        return view;
                    }

                    @NonNull
                    @Override
                    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                        View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                        final TextView text = view.findViewById(R.id.spinner_tv);
                        text.setText(unitList.get(position).getName());
                        unitName=unitList.get(position).getName();
                        return view;
                    }
                };
                newAddGoodCompany.setAdapter(arrayAdapter);
                newAddGoodIsSku.setClickable(false);
                newAddGoodIsSku.setFocusable(false);
                newAddGoodIsSerial.setClickable(false);
                newAddGoodIsSerial.setFocusable(false);
            } else {
                newAddGoodGoodsNum.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                newAddGoodMoreNum.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                newAddGoodLessNum.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
                newAddGoodIsSku.setClickable(true);
                newAddGoodIsSku.setFocusable(true);
                newAddGoodWeightLin.setVisibility(View.VISIBLE);
//                setEditType(newAddGoodMoreNum);
//                setEditType(newAddGoodLessNum);
                getUnitSelect();
//                newAddGoodIsSku.setClickable(false);
                if (newAddGoodSplitState.isChecked()){
                    newAddGoodIsSerial.setClickable(false);
                    newAddGoodIsSerial.setFocusable(false);
                }else {
                    newAddGoodIsSerial.setClickable(true);
                    newAddGoodIsSerial.setFocusable(true);
                }
            }
        });

        newAddGoodIsSerial.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isChecked) {
                newAddGoodGoodsNum.setClickable(true);
                newAddGoodGoodsNum.setFocusable(true);
                newAddGoodGoodsNum.setFocusableInTouchMode(true);
//                newAddGoodGoodsNum.requestFocus();
                newAddGoodIsWeight.setClickable(true);
                newAddGoodIsWeight.setFocusable(true);
                newAddGoodSplitState.setClickable(true);
                newAddGoodSplitState.setFocusable(true);
            }else {
                newAddGoodGoodsNum.setText("");
                newAddGoodGoodsNum.setClickable(false);
                newAddGoodGoodsNum.setFocusable(false);
                newAddGoodIsWeight.setClickable(false);
                newAddGoodIsWeight.setFocusable(false);
                newAddGoodSplitState.setClickable(false);
                newAddGoodSplitState.setFocusable(false);
            }
            if (skuGoodsAdapter!=null){
                skuGoodsAdapter.setIsSerial(isChecked);
            }
            setSkuGoodsAdapter();
        });

//        newAddGoodGoodsNum.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before, int count) {
//
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//                if (newAddGoodGoodsNum.getText().toString().contains(".")){
//                    newAddGoodIsWeight.setClickable(false);
//                    newAddGoodIsWeight.setFocusable(false);
//                }else {
//                    newAddGoodIsWeight.setClickable(true);
//                    newAddGoodIsWeight.setFocusable(true);
//                }
//            }
//        });

//        newAddGoodSplitState.setOnCheckedChangeListener((buttonView, isChecked) -> {
//            if (!isChecked) {
//                newAddGoodIsWeight.setClickable(true);
//                newAddGoodIsWeight.setFocusable(true);
//                newAddGoodIsSerial.setClickable(true);
//                newAddGoodIsSerial.setFocusable(true);
//
//            }else {
////                newAddGoodIsWeight.setChecked(false);
////                newAddGoodSplitState.setChecked(false);
//                newAddGoodIsWeight.setClickable(false);
//                newAddGoodIsWeight.setFocusable(false);
//                newAddGoodIsSerial.setClickable(false);
//                newAddGoodIsSerial.setFocusable(false);
//            }
//        });

        newAddGoodIsSku.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isChecked) {
                skuGoodsList.clear();
                setSkuGoodsAdapter();
                newAddGoodSkuSetting.setVisibility(View.GONE);
                newAddGoodSkuGoodsLin.setVisibility(View.GONE);
                if ("2".equals(aCache.getAsString("platform_type"))){
                    linQ3.setVisibility(View.VISIBLE);
                }else {
                    linQ3.setVisibility(View.GONE);
                }
                newAddGoodIsWeight.setClickable(true);
                newAddGoodIsWeight.setFocusable(true);
            }else {
                linQ3.setVisibility(View.GONE);
                newAddGoodIsWeight.setClickable(false);
                newAddGoodIsWeight.setFocusable(false);
                newAddGoodSkuSetting.setVisibility(View.VISIBLE);
                newAddGoodSkuGoodsLin.setVisibility(View.VISIBLE);
            }
        });

        newAddGoodRetailState.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isChecked) {
                newAddTab.setVisibility(View.INVISIBLE);
            }else {
                newAddTab.setVisibility(View.VISIBLE);
            }
        });

//        newAddGoodOnlineState.setOnCheckedChangeListener((buttonView, isChecked) -> {
//            if (!isChecked) {
//                newAddTab1.setVisibility(View.GONE);
//            }else {
//                newAddTab1.setVisibility(View.VISIBLE);
//            }
//        });

        newAddGoodShopMemStatus.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (skuGoodsAdapter!=null){
                skuGoodsAdapter.setmStatus(newAddGoodShopMemStatus.isChecked(),
                        newAddGoodStoreMemStatus.isChecked(),newAddGoodPlusMemStatus.isChecked());
                setSkuGoodsAdapter();
            }
        });
        newAddGoodStoreMemStatus.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (skuGoodsAdapter!=null){
                skuGoodsAdapter.setmStatus(newAddGoodShopMemStatus.isChecked(),
                        newAddGoodStoreMemStatus.isChecked(),newAddGoodPlusMemStatus.isChecked());
                setSkuGoodsAdapter();
            }
        });
        newAddGoodPlusMemStatus.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (skuGoodsAdapter!=null){
                skuGoodsAdapter.setmStatus(newAddGoodShopMemStatus.isChecked(),
                        newAddGoodStoreMemStatus.isChecked(),newAddGoodPlusMemStatus.isChecked());
                setSkuGoodsAdapter();
            }
        });
        newAddGoodDelivery3.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                newAddGoodDeliveryView.setVisibility(View.VISIBLE);
                newAddGoodDeliveryLinear.setVisibility(View.VISIBLE);
            } else {
                newAddGoodDeliveryView.setVisibility(View.GONE);
                newAddGoodDeliveryLinear.setVisibility(View.GONE);
            }
        });
        newAddGoodOnlineState.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                newAddTab1.setVisibility(View.VISIBLE);
                if ("2".equals(aCache.getAsString("userType"))||"3".equals(aCache.getAsString("userType"))) {
                    newAddGoodAdvanceSaleStatus.setVisibility(View.VISIBLE);
                } else {
                    newAddGoodAdvanceSaleStatus.setChecked(false);
                    newAddGoodAdvanceSaleStatus.setVisibility(View.GONE);
                }
                if ("1".equals(aCache.getAsString("userType"))){
                    newAddGoodAdvanceSaleStatus.setChecked(false);
                    newAddGoodAdvanceSaleStatus.setVisibility(View.GONE);
                }
            }else {
                newAddTab1.setVisibility(View.INVISIBLE);
                newAddGoodAdvanceSaleStatus.setVisibility(View.INVISIBLE);
            }
        });
        newAddGoodSplitState.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (!isChecked) {
//                newAddGoodIsWeight.setClickable(true);
//                newAddGoodIsWeight.setFocusable(true);
                newAddGoodIsSerial.setClickable(true);
                newAddGoodIsSerial.setFocusable(true);

            }else {
//                newAddGoodIsWeight.setChecked(false);
//                newAddGoodSplitState.setChecked(false);
//                newAddGoodIsWeight.setClickable(false);
//                newAddGoodIsWeight.setFocusable(false);
                newAddGoodIsSerial.setClickable(false);
                newAddGoodIsSerial.setFocusable(false);
            }
//            if (newAddGoodIsWeight.isChecked()) {
//                Toast.makeText(context, "稱重商品無法拆分", Toast.LENGTH_SHORT).show();
//                newAddGoodSplitState.setChecked(false);
//                newAddGoodIsSerial.setClickable(false);
//                newAddGoodIsSerial.setFocusable(false);
//            }else {
//                if (newAddGoodIsWeight.isChecked()){
//                    newAddGoodIsSerial.setClickable(false);
//                    newAddGoodIsSerial.setFocusable(false);
//                }else {
//                    newAddGoodIsSerial.setClickable(true);
//                    newAddGoodIsSerial.setFocusable(true);
//                }
//            }
        });
        newAddGoodGoodsNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (newAddGoodGoodsNum.getText().toString().trim().contains(".")){
                    newAddGoodIsWeight.setClickable(false);
                    newAddGoodIsWeight.setFocusable(false);
                }

            }
        });
        newAddGoodGuideRoyaltyCustom.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (skuGoodsAdapter!=null){
                skuGoodsAdapter.setGuide(isChecked);
            }
            setSkuGoodsAdapter();
            if (isChecked) {
                newAddGoodGuideView1.setVisibility(View.VISIBLE);
                newAddGoodGuideView2.setVisibility(View.VISIBLE);
                newAddGoodGuideLinear1.setVisibility(View.VISIBLE);
                newAddGoodGuideLinear2.setVisibility(View.VISIBLE);
            } else {
                newAddGoodGuideRoyaltyPrice.setText("");
                newAddGoodGuideRoyaltyOnlinePrice.setText("");
                newAddGoodGuideView1.setVisibility(View.GONE);
                newAddGoodGuideView2.setVisibility(View.GONE);
                newAddGoodGuideLinear1.setVisibility(View.GONE);
                newAddGoodGuideLinear2.setVisibility(View.GONE);
            }
        });
    }

    private void setTextListener1(EditText editText){
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                String temp = editText.getText().toString();
                int posDot = temp.indexOf(".");
                if (posDot <= 0) return;
                if (temp.length() - posDot - 1 > 2) {
                    editText.setText(temp.substring(0,posDot+3));
                    editText.setSelection(posDot+3);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }
    private void setTextListener2(EditText editText){
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                String temp = editText.getText().toString();
                int posDot = temp.indexOf(".");
                if (posDot <= 0) return;
                if (temp.length() - posDot - 1 > 3) {
                    editText.setText(temp.substring(0,posDot+4));
                    editText.setSelection(posDot+4);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (editText==newAddGoodGoodsNum||editText==newAddGoodMoreNum||editText==newAddGoodLessNum){
                    if (newAddGoodGoodsNum.getText().toString().contains(".")||newAddGoodMoreNum.getText().toString().contains(".")
                            ||newAddGoodLessNum.getText().toString().contains(".")){
                        newAddGoodIsWeight.setClickable(false);
                        newAddGoodIsWeight.setClickable(false);
                    }else {
                        newAddGoodIsWeight.setClickable(true);
                        newAddGoodIsWeight.setClickable(true);
                    }
                }
            }
        });
    }

    private void setAdapterClick(GridImageAdapter gridImageAdapter){
        gridImageAdapter.setOnItemClickListener((v, position) -> {
            List<LocalMedia> selectList = gridImageAdapter.getData();
            if (selectList.size() > 0) {
                LocalMedia media = selectList.get(position);
                String mimeType = media.getMimeType();
                int mediaType = PictureMimeType.getMimeType(mimeType);
                switch (mediaType) {
                    case PictureConfig.TYPE_VIDEO:
                        // 預覽視頻
                        PictureSelector.create(NewAddGoodActivity.this)
                                .themeStyle(R.style.picture_default_style)
//                                .setPictureStyle(mPictureParameterStyle)// 動態自定義相冊主題
                                .externalPictureVideo(TextUtils.isEmpty(media.getAndroidQToPath()) ? media.getPath() : media.getAndroidQToPath());
                        break;
                    case PictureConfig.TYPE_AUDIO:
                        // 預覽音頻
                        PictureSelector.create(NewAddGoodActivity.this)
                                .externalPictureAudio(PictureMimeType.isContent(media.getPath()) ? media.getAndroidQToPath() : media.getPath());
                        break;
                    default:
                        // 預覽圖片 可自定長按保存路徑
//                        PictureWindowAnimationStyle animationStyle = new PictureWindowAnimationStyle();
//                        animationStyle.activityPreviewEnterAnimation = R.anim.picture_anim_up_in;
//                        animationStyle.activityPreviewExitAnimation = R.anim.picture_anim_down_out;
                        PictureSelector.create(NewAddGoodActivity.this)
                                .themeStyle(R.style.picture_default_style) // xml設置主題
//                                .setPictureStyle(mPictureParameterStyle)// 動態自定義相冊主題
                                //.setPictureWindowAnimationStyle(animationStyle)// 自定義頁面啓動動畫
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)// 設置相冊Activity方向，不設置默認使用系統
                                .isNotPreviewDownload(true)// 預覽圖片長按是否可以下載
                                //.bindCustomPlayVideoCallback(new MyVideoSelectedPlayCallback(getContext()))// 自定義播放回調控制，用戶可以使用自己的視頻播放界面
                                .imageEngine(GlideEngine.createGlideEngine())// 外部傳入圖片加載引擎，必傳項
                                .openExternalPreview(position, selectList);
                        break;
                }
            }
        });
    }

    @OnClick({R.id.title_back, R.id.newAddGood_barcodeIv, R.id.newAddGood_classification, R.id.newAddGood_cover,
            R.id.newAddGood_video, R.id.newAddGood_banner, R.id.newAddGood_skuSetting, R.id.newAddGood_commitAndFinish,
            R.id.newAddGood_commit,R.id.newAddGood_autoFreightNumber})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.newAddGood_classification:
                intent = new Intent(context, ClassificationActivity.class);
                startActivityForResult(intent, 100);
                break;
            case R.id.newAddGood_cover:
                break;
            case R.id.newAddGood_video:
                break;
            case R.id.newAddGood_banner:
                break;
            case R.id.newAddGood_skuSetting:
                    chooseTagDialogFragment = new ChooseTagDialogFragment(2,skuInfoNews);
                    chooseTagDialogFragment.setFragmentHook(this);
                    chooseTagDialogFragment.show(getFragmentManager(), "ChooseTag");
                break;
            case R.id.newAddGood_commitAndFinish:
                checkGood(1);
                break;
            case R.id.newAddGood_commit:
                checkGood(2);
                break;
            case R.id.newAddGood_barcodeIv:
                startQrCode();
                break;
            case R.id.newAddGood_autoFreightNumber:
                newAddGoodFreightNumber.setText(String.valueOf((int)((Math.random() * 9 + 1) * 100000)));
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 攝像頭權限申請
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 獲得授權
                    startQrCode();
                } else {
                    // 被禁止授權
                    Toast.makeText(context, "請至權限中心打開本應用的相機訪問權限", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }


    private void checkGood(int type) {
        if (TextUtils.isEmpty(newAddGoodName.getText().toString().trim())) {
            Toast.makeText(context, "請輸入商品名稱", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(newAddGoodFreightNumber.getText().toString().trim())) {
            Toast.makeText(context, "請輸入商品貨號", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(classId)) {
            Toast.makeText(context, "請選擇商品分類", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodRetailState.isChecked() && TextUtils.isEmpty(newAddGoodRetailPrice.getText().toString().trim())) {
            Toast.makeText(context, "開啓店內出售必須輸入店內零售價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodOnlineState.isChecked() && TextUtils.isEmpty(newAddGoodShopPrice.getText().toString().trim())) {
            Toast.makeText(context, "開啓商城出售必須輸入商城零售價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!"1".equals(aCache.getAsString("userType"))) {
            if (newAddGoodOnlineState.isChecked() && !(newAddGoodDelivery1.isChecked() || newAddGoodDelivery2.isChecked() || newAddGoodDelivery3.isChecked())) {
                Toast.makeText(context, "請選擇配送方式", Toast.LENGTH_SHORT).show();
                return;
            }
        }
        if (newAddGoodIntegralStatus.isChecked() && TextUtils.isEmpty(newAddGoodIntegral.getText().toString().trim())) {
            Toast.makeText(context, "請輸入贈送數量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodIsWeight.isChecked() && unitList.get(unitIndex).getName().equals("請選擇單位")) {
            Toast.makeText(context, "請選擇單位", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodDelivery3.isChecked() && storeFreightIndex == 0) {
            Toast.makeText(context, "請選擇配送模板", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!TextUtils.isEmpty(newAddGoodGoodsNum.getText().toString().trim()) &&
                TextUtils.isEmpty(newAddGoodPurchasePrice.getText().toString().trim())) {
            Toast.makeText(context, "請輸入商品進貨價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!TextUtils.isEmpty(newAddGoodMoreNum.getText().toString().trim()) &&
                Double.parseDouble(newAddGoodMoreNum.getText().toString().trim())>100000000) {
            Toast.makeText(context, "庫存超量不能大於一億", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!TextUtils.isEmpty(newAddGoodLessNum.getText().toString().trim()) &&
                Double.parseDouble(newAddGoodLessNum.getText().toString().trim())>100000000) {
            Toast.makeText(context, "庫存預警不能大於一億", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(newAddGoodGoodsOrder.getText().toString().trim())) {
            newAddGoodGoodsOrder.setText("1");
        }
        if (newAddGoodStoreMemStatus.isChecked() && TextUtils.isEmpty(newAddGoodStoreMemPrice.getText().toString().trim())) {
            Toast.makeText(context, "請輸入店內會員價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodStoreMemStatus.isChecked() && !TextUtils.isEmpty(newAddGoodRetailPrice.getText().toString().trim()) && (Double.parseDouble(newAddGoodRetailPrice.getText().toString().trim())<
                Double.parseDouble(newAddGoodStoreMemPrice.getText().toString().trim()))) {
            Toast.makeText(context, "店內會員價不能大於店內零售價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodShopMemStatus.isChecked() && TextUtils.isEmpty(newAddGoodShopMemPrice.getText().toString().trim())) {
            Toast.makeText(context, "請輸入商城會員價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodShopMemStatus.isChecked() &&!TextUtils.isEmpty(newAddGoodShopPrice.getText().toString().trim()) && (Double.parseDouble(newAddGoodShopPrice.getText().toString().trim())<
                Double.parseDouble(newAddGoodShopMemPrice.getText().toString().trim()))) {
            Toast.makeText(context, "商城會員價不能大於商城零售價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodPlusMemStatus.isChecked() && TextUtils.isEmpty(newAddGoodPlusMemPrice.getText().toString().trim())) {
            Toast.makeText(context, "請輸入Plus會員價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodPlusMemStatus.isChecked() &&!TextUtils.isEmpty(newAddGoodRetailPrice.getText().toString().trim()) && (Double.parseDouble(newAddGoodPlusMemPrice.getText().toString().trim())>
                Double.parseDouble(newAddGoodRetailPrice.getText().toString().trim()))) {
            Toast.makeText(context, "plus會員價不能大於店內零售價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodPlusMemStatus.isChecked() &&!TextUtils.isEmpty(newAddGoodShopPrice.getText().toString().trim()) && (Double.parseDouble(newAddGoodPlusMemPrice.getText().toString().trim())>
                Double.parseDouble(newAddGoodShopPrice.getText().toString().trim()))) {
            Toast.makeText(context, "plus會員價不能大於商城零售價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodPlusMemStatus.isChecked() &&!TextUtils.isEmpty(newAddGoodStoreMemPrice.getText().toString().trim()) && (Double.parseDouble(newAddGoodPlusMemPrice.getText().toString().trim())>
                Double.parseDouble(newAddGoodStoreMemPrice.getText().toString().trim()))) {
            Toast.makeText(context, "plus會員價不能大於店內會員價", Toast.LENGTH_SHORT).show();
            return;
        }
        if (newAddGoodPlusMemStatus.isChecked() &&!TextUtils.isEmpty(newAddGoodShopMemPrice.getText().toString().trim()) && (Double.parseDouble(newAddGoodPlusMemPrice.getText().toString().trim())>
                Double.parseDouble(newAddGoodShopMemPrice.getText().toString().trim()))) {
            Toast.makeText(context, "plus會員價不能大於商城會員價", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (newAddGoodIntegralStatus.isChecked() && TextUtils.isEmpty(newAddGoodShopMemPrice.getText().toString().trim())) {
//            Toast.makeText(context, "請輸入商城會員價", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (newAddGoodGuideRoyaltyCustom.isChecked()) {
//            if (!newAddGoodRetailState.isChecked() || TextUtils.isEmpty(newAddGoodRetailPrice.getText().toString().trim())) {
//                Toast.makeText(context, "請先開啓店內出售並輸入店內零售價", Toast.LENGTH_SHORT).show();
//                return;
//            }
            if (TextUtils.isEmpty(newAddGoodGuideRoyaltyPrice.getText().toString().trim())) {
                Toast.makeText(context, "請輸入線下提成", Toast.LENGTH_SHORT).show();
                return;
            }
//            if (Double.parseDouble(newAddGoodGuideRoyaltyPrice.getText().toString().trim()) >
//                    Double.parseDouble(newAddGoodRetailPrice.getText().toString().trim())) {
//                Toast.makeText(context, "線下提成不能大於店內零售價", Toast.LENGTH_SHORT).show();
//                return;
//            }
        }
        if (newAddGoodGuideRoyaltyCustom.isChecked()) {
//            if (!newAddGoodOnlineState.isChecked() || TextUtils.isEmpty(newAddGoodShopPrice.getText().toString().trim())) {
//                Toast.makeText(context, "請先開啓商城出售並輸入商城零售價", Toast.LENGTH_SHORT).show();
//                return;
//            }
            if (TextUtils.isEmpty(newAddGoodGuideRoyaltyOnlinePrice.getText().toString().trim())) {
                Toast.makeText(context, "請輸入線上提成", Toast.LENGTH_SHORT).show();
                return;
            }
//            if (Double.parseDouble(newAddGoodGuideRoyaltyOnlinePrice.getText().toString().trim()) >
//                    Double.parseDouble(newAddGoodRetailPrice.getText().toString().trim())) {
//                Toast.makeText(context, "線上提成不能大於商城零售價", Toast.LENGTH_SHORT).show();
//                return;
//            }
        }
        if (newAddGoodIsSku.isChecked()) {
            if (skuGoodsList.size() == 0) {
                Toast.makeText(context, "請重新選擇規格信息", Toast.LENGTH_SHORT).show();
            } else {
                for (int i = 0; i < skuGoodsList.size(); i++) {
                    if (TextUtils.isEmpty(skuGoodsList.get(i).getFreightNumber())) {
                        Toast.makeText(context, "請輸入第"+(i+1)+"個規格的商品貨號", Toast.LENGTH_SHORT).show();
                        newAddGoodSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                        return;
                    }
                    if ("2".equals(aCache.getAsString("platform_type"))&&TextUtils.isEmpty(skuGoodsList.get(i).getThird_goods_code())) {
                        Toast.makeText(context, "請輸入第"+(i+1)+"個規格的Q3編碼", Toast.LENGTH_SHORT).show();
                        newAddGoodSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                        return;
                    }
                    if ("1".equals(aCache.getAsString("userType"))){
                        if (!TextUtils.isEmpty(skuGoodsList.get(i).getGoods_num()) && Double.parseDouble(skuGoodsList.get(i).getGoods_num()) > 0 && TextUtils.isEmpty(skuGoodsList.get(i).getPurch_price())) {
                            Toast.makeText(context, "請輸入第" + (i + 1) + "個規格的商品進價", Toast.LENGTH_SHORT).show();
                            newAddGoodSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                            return;
                        }
                    }else{
                        if (!TextUtils.isEmpty(skuGoodsList.get(i).getGoods_num()) && Double.parseDouble(skuGoodsList.get(i).getGoods_num()) > 0 && TextUtils.isEmpty(skuGoodsList.get(i).getPurchasePrice())) {
                            Toast.makeText(context, "請輸入第" + (i + 1) + "個規格的商品進價", Toast.LENGTH_SHORT).show();
                            newAddGoodSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                            return;
                        }
                    }
                    if (!TextUtils.isEmpty(skuGoodsList.get(i).getMore_num()) &&
                            Double.parseDouble(skuGoodsList.get(i).getMore_num())>100000000) {
                        Toast.makeText(context, "庫存超量不能大於一億", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (!TextUtils.isEmpty(skuGoodsList.get(i).getLess_num()) &&
                            Double.parseDouble(skuGoodsList.get(i).getLess_num())>100000000) {
                        Toast.makeText(context, "庫存預警不能大於一億", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (TextUtils.isEmpty(skuGoodsList.get(i).getPrice()) && newAddGoodRetailState.isChecked()) {
                        Toast.makeText(context, "請輸入第"+(i+1)+"個規格的商品零售價", Toast.LENGTH_SHORT).show();
                        newAddGoodSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                        return;
                    }
                    if (newAddGoodRetailState.isChecked()&&(TextUtils.isEmpty(skuGoodsList.get(i).getPrice()) || Double.parseDouble(skuGoodsList.get(i).getPrice()) <= 0)) {
                        Toast.makeText(context, skuGoodsList.get(i).getName() + "的售價不正確", Toast.LENGTH_SHORT).show();
                        newAddGoodSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                        return;
                    }
                    if (TextUtils.isEmpty(skuGoodsList.get(i).getStock())) {
                        skuGoodsList.get(i).setStock("0");
                        return;
                    }
                    if (TextUtils.isEmpty(skuGoodsList.get(i).getOnline_price()) && newAddGoodOnlineState.isChecked()) {
                        Toast.makeText(context, "請輸入第"+(i+1)+"個規格的商品商城價", Toast.LENGTH_SHORT).show();
                        newAddGoodSkuGoodsListView.smoothScrollToPositionFromTop(i, 0);
                        return;
                    }
                    if (newAddGoodStoreMemStatus.isChecked() && TextUtils.isEmpty(skuGoodsList.get(i).getStore_mem_price())) {
                        Toast.makeText(context, "請輸入第"+(i+1)+"個規格的店內會員價", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (newAddGoodStoreMemStatus.isChecked()&&!TextUtils.isEmpty(skuGoodsList.get(i).getPrice())&&newAddGoodRetailState.isChecked() && (Double.parseDouble(skuGoodsList.get(i).getPrice())<
                            Double.parseDouble(skuGoodsList.get(i).getStore_mem_price()))) {
                        Toast.makeText(context, "店內會員價不能大於店內零售價", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (newAddGoodShopMemStatus.isChecked() && TextUtils.isEmpty(skuGoodsList.get(i).getShop_mem_price())) {
                        Toast.makeText(context, "請輸入第"+(i+1)+"個規格的商城會員價", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (newAddGoodShopMemStatus.isChecked()&&!TextUtils.isEmpty(skuGoodsList.get(i).getOnline_price())&&newAddGoodOnlineState.isChecked() && (Double.parseDouble(skuGoodsList.get(i).getOnline_price())<
                            Double.parseDouble(skuGoodsList.get(i).getShop_mem_price()))) {
                        Toast.makeText(context, "商城會員價不能大於商城零售價", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (newAddGoodPlusMemStatus.isChecked() && TextUtils.isEmpty(skuGoodsList.get(i).getPlus_price())) {
                        Toast.makeText(context, "請輸入第"+(i+1)+"個規格的Plus會員價", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (newAddGoodPlusMemStatus.isChecked() &&!TextUtils.isEmpty(skuGoodsList.get(i).getPrice())&&newAddGoodRetailState.isChecked() && (Double.parseDouble(skuGoodsList.get(i).getPlus_price())>
                            Double.parseDouble(skuGoodsList.get(i).getPrice()))) {
                        Toast.makeText(context, "plus會員價不能大於店內零售價", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (newAddGoodPlusMemStatus.isChecked() &&!TextUtils.isEmpty(skuGoodsList.get(i).getOnline_price())&&newAddGoodOnlineState.isChecked() && (Double.parseDouble(skuGoodsList.get(i).getPlus_price())>
                            Double.parseDouble(skuGoodsList.get(i).getOnline_price()))) {
                        Toast.makeText(context, "plus會員價不能大於商城零售價", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (newAddGoodPlusMemStatus.isChecked() &&newAddGoodStoreMemStatus.isChecked() && (Double.parseDouble(skuGoodsList.get(i).getPlus_price())>
                            Double.parseDouble(skuGoodsList.get(i).getStore_mem_price()))) {
                        Toast.makeText(context, "plus會員價不能大於店內會員價", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (newAddGoodPlusMemStatus.isChecked() &&newAddGoodShopMemStatus.isChecked() && (Double.parseDouble(skuGoodsList.get(i).getPlus_price())>
                            Double.parseDouble(skuGoodsList.get(i).getShop_mem_price()))) {
                        Toast.makeText(context, "plus會員價不能大於商城會員價", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (newAddGoodGuideRoyaltyCustom.isChecked()) {
                        if (TextUtils.isEmpty(skuGoodsList.get(i).getGuide_royalty_price())) {
                            Toast.makeText(context, "請輸入第"+(i+1)+"個規格的線下提成", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                    if (newAddGoodGuideRoyaltyCustom.isChecked()) {
                        if (TextUtils.isEmpty(skuGoodsList.get(i).getGuide_royalty_online_price())) {
                            Toast.makeText(context, "請輸入第"+(i+1)+"個規格的線上提成", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                }
            }
        }
        addGood(type);
    }

    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                        if (skuGoodsAdapter!=null) {
                            skuGoodsAdapter.setshowSet(editSet);
                        }
                        setSkuGoodsAdapter();
//                        if ("1".equals(aCache.getAsString("userType"))){
//                            newAddGoodDeliveryAllLinear.setVisibility(View.GONE);
//                            newAddGoodSaleRuleView1.setVisibility(View.GONE);
//                            newAddGoodSaleRuleLinear1.setVisibility(View.GONE);
//                            newAddGoodSaleRuleView2.setVisibility(View.GONE);
//                            newAddGoodSaleRuleLinear2.setVisibility(View.GONE);
//
//                            newAddGoodIntegralView1.setVisibility(View.GONE);
//                            newAddGoodIntegralLinear1.setVisibility(View.GONE);
//                            newAddGoodIntegralView2.setVisibility(View.GONE);
//                            newAddGoodIntegralLinear2.setVisibility(View.GONE);
//
//                            newAddGoodGuideView.setVisibility(View.GONE);
//                            newAddGoodGuideLinear.setVisibility(View.GONE);
//                        }else {
                            initLayout(editSet.getData().getGoods_integral_state());
//                        }
//                        if (!TextUtils.isEmpty(goodId)){
                            if (editSet.getData().getEdit_price()!=null&&!TextUtils.isEmpty(editSet.getData().getEdit_price())&&
                                    Integer.parseInt(editSet.getData().getEdit_price())==2){
                                newAddGoodRetailState.setChecked(false);
                                newAddGoodOnlineState.setChecked(false);
                                newAddGoodRetailPrice.setClickable(false);
                                newAddGoodRetailPrice.setFocusable(false);
                                newAddGoodShopPrice.setClickable(false);
                                newAddGoodShopPrice.setFocusable(false);
                                newAddGoodPurchasePrice.setClickable(false);
                                newAddGoodPurchasePrice.setFocusable(false);
                                price_set.setVisibility(View.VISIBLE);
                                newAddGoodIntegralStatus.setClickable(false);
                                newAddGoodIntegralStatus.setFocusable(false);
                                newAddGoodIntegral.setClickable(false);
                                newAddGoodIntegral.setFocusable(false);
                            }
                            if (editSet.getData().getShow_purchase_price()!=null&&!TextUtils.isEmpty(editSet.getData().getShow_purchase_price())&&
                                    Integer.parseInt(editSet.getData().getShow_purchase_price())==2){
                                linPurchasePrice.setVisibility(View.GONE);
                            }
//                        }
                        if ((editSet.getData().getIntegral_arrive_cash()!=null
                                &&!TextUtils.isEmpty(editSet.getData().getIntegral_arrive_cash())&&
                                Integer.parseInt(editSet.getData().getIntegral_arrive_cash())==2)||
                                (editSet.getData().getMarketing_methods()!=null&&!TextUtils.isEmpty(editSet.getData().getMarketing_methods())&&
                                Integer.parseInt(editSet.getData().getMarketing_methods())==1)){

                            newAddGoodStoreMemIntegralLin.setVisibility(View.GONE);
                            newAddGoodPlusMemIntegralLin.setVisibility(View.GONE);
                            newAddGoodShopMemIntegralLin.setVisibility(View.GONE);
                        }
                        if (editSet.getData().getSupplier_type()!=null&&!TextUtils.isEmpty(editSet.getData().getSupplier_type())&&!"1".equals(aCache.getAsString("userType"))&&Integer.parseInt(editSet.getData().getSupplier_type())==2){
                            newAddGoodGoodsNum.setClickable(false);
                            newAddGoodGoodsNum.setFocusable(false);
                        }
                    break;
                case 2:
                    View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, null, false);
                    final TextView text = view.findViewById(R.id.spinner_tv);
                    text.setText((String)msg.obj);
                    break;
                case 3:
                    try{
                        JSONObject jsonObject=new JSONObject((String) msg.obj).getJSONObject("data");
                        JSONArray jsonArray=jsonObject.getJSONArray("list");
                        for (int i=0;i<jsonArray.length();i++){
                            SkuGoodsInfo skuGoodsInfo=GsonUtils.JsonToBean(jsonArray.get(i).toString(),SkuGoodsInfo.class);
                            skuGoodsList.add(skuGoodsInfo);
                        }
                        newAddGoodSkuGoodsLin.setVisibility(View.VISIBLE);
                        setSkuGoodsAdapter();
                        skuGoodsAdapter.setmStatus(newAddGoodShopMemStatus.isChecked(),
                                newAddGoodStoreMemStatus.isChecked(),newAddGoodPlusMemStatus.isChecked());
                        setSkuGoodsAdapter();
                    }catch (JSONException e){
                        e.printStackTrace();
                    }
                    break;
                case 4:
                    if (!TextUtils.isEmpty(newVideoPath))
                    uploadFile(2, new File(newVideoPath),(List<LocalMedia>)msg.obj);
                    break;
                case 5:
                    tint.setText((String)msg.obj);
                    if ("上傳成功".equals((String)msg.obj)){
                        dialogText.setVisibility(View.GONE);
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void goodInfoSet(){
        loadingDialog.show();
           try{
               JSONObject jsonObject=new JSONObject();
               jsonObject.put("cashier_id",aCache.getAsString("uid"));
               HttpUtils.post(context, Common.GET_GOOD_SET, Tools.createParameterCode(jsonObject), new TextCallBack() {
                   @Override
                   protected void onSuccess(String text) {
                       loadingDialog.dismiss();
                           Log.d("商品編輯設置",text);
                           //{"status":1.0,"msg":"獲取成功","data":{"integral_arrive_cash":0.0,"marketing_methods":"1"}}
                           editSet=GsonUtils.JsonToBean(text,EditSet.class);
                           if (editSet.getStatus() == 1) {
                               Message message=new Message();
                               message.what=1;
                               handler.sendMessage(message);
                           }else {
                               Toast.makeText(context,editSet.getMsg(),Toast.LENGTH_SHORT).show();
                           }
                   }

                   @Override
                   protected void onFailure(ResponseException e) {
                       loadingDialog.dismiss();
                   }
               });
           }catch (JSONException e){
               e.printStackTrace();
           }
    }

    private void goodInfoSku(String goodsId){
        loadingDialog.show();
        try {
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("cashier_id",aCache.getAsString("uid"));
            jsonObject.put("goods_id",goodsId);
            if ("1".equals(aCache.getAsString("userType"))){
                jsonObject.put("managerType","3");
            }else {
                jsonObject.put("managerType","4");
            }
            HttpUtils.post(context, Common.GET_GOOD_SKU, Tools.createParameterCode(jsonObject), new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            Message message=new Message();
                            message.what=3;
                            message.obj=text;
                            handler.sendMessage(message);
                        }else {
                            Toast.makeText(context,json.getString("message"),Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        }catch (JSONException e){
            e.printStackTrace();
        }
    }

    //添加商品
    private void addGood(final int type) {
        if ("2".equals(aCache.getAsString("platform_type"))&&"".equals(newAddGoodQ3.getText().toString().trim())&&!newAddGoodIsSku.isChecked()){
            Toast.makeText(this,"請輸入Q3編碼",Toast.LENGTH_SHORT).show();
            return;
        }
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        try {
//            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                if ("1".equals(aCache.getAsString("userType"))) {
                    jsonObject.put("managerType", 3);//3商戶 4門店
                } else {
                    jsonObject.put("managerType", 4);//3商戶 4門店
                }
//            }
            if (!"".equals(newAddGoodQ3.getText().toString().trim())&&!newAddGoodIsSku.isChecked()){
                jsonObject.put("third_goods_code", newAddGoodQ3.getText().toString().trim());//Q3編碼
                jsonObject.put("platform_type", aCache.getAsString("platform_type"));//Q3編碼
            }
            jsonObject.put("status", "1");
            jsonObject.put("user_type", aCache.getAsString("userType"));//1商戶 2店長 3收銀員
            jsonObject.put("operate_id", aCache.getAsString("operator_id"));
            jsonObject.put("id", goodId);//	商品id 編輯時候傳
            jsonObject.put("goods_name", newAddGoodName.getText().toString().trim());
            jsonObject.put("subheading", newAddGoodSubheading.getText().toString().trim());//副標題
            jsonObject.put("goods_number", newAddGoodFreightNumber.getText().toString().trim());
            jsonObject.put("goods_code", newAddGoodCode.getText().toString().trim());
            jsonObject.put("goods_class_id", classId);//商品分類id
            jsonObject.put("purchase_price", newAddGoodPurchasePrice.getText().toString().trim());
            jsonObject.put("label_id", labelIndex == 0 ? "" : labelList.get(labelIndex).getId());//標籤id
            jsonObject.put("retail_price", newAddGoodRetailPrice.getText().toString().trim());//店內零售價
            jsonObject.put("goods_brand_id", brandIndex == 0 ? "" : brandList.get(brandIndex).getId());//品牌id
            jsonObject.put("online_price", newAddGoodShopPrice.getText().toString().trim());//商城零售價
            jsonObject.put("goods_order", newAddGoodGoodsOrder.getText().toString().trim());//	商城排序
            jsonObject.put("supplier_id", "");//供貨商
            jsonObject.put("goods_yieldly_id", yieldlyIndex == 0 ? "" : yieldlyList.get(yieldlyIndex).getId());//產地
            jsonObject.put("more_num", newAddGoodMoreNum.getText().toString().trim());//庫存超量
            jsonObject.put("less_num", newAddGoodLessNum.getText().toString().trim());//庫存預警
            jsonObject.put("company", unitList.get(unitIndex).getName());//單位
            jsonObject.put("weight_value", newAddGoodWeightValue.getText().toString().trim());//重量
            jsonObject.put("goods_num", newAddGoodGoodsNum.getText().toString().trim());//庫存
            jsonObject.put("fictitious_num", newAddGoodFictiousNum.getText().toString().trim());//虛擬銷量
            jsonObject.put("specifications", newAddGoodSkuEdit.getText().toString().trim());//規格
            jsonObject.put("pricing_method", newAddGoodIsWeight.isChecked() ? 2 : 1);//如果開啓稱重 商品單位爲必選 同時隱藏 "重量"
            jsonObject.put("plu_code", newAddGoodPluIndex.getText().toString().trim());//PLU秤序號
            jsonObject.put("status", newAddGoodStatus.isChecked() ? 0 : 1);
            jsonObject.put("retail_state", newAddGoodRetailState.isChecked() ? 1 : 0);//是否開啓店內出售
            jsonObject.put("online_state", newAddGoodOnlineState.isChecked() ? 1 : 0);//是否在商城中出售
            jsonObject.put("serial_number_state", newAddGoodIsSerial.isChecked() ? 1 : 0);//是否在商城中出售
            if ("2".equals(aCache.getAsString("userType"))||"3".equals(aCache.getAsString("userType"))) {
                jsonObject.put("advance_sale_status", newAddGoodAdvanceSaleStatus.isChecked() ? 1 : 0);//是否商城預售
                jsonObject.put("split_state", newAddGoodSplitState.isChecked() ? 1 : 0);//是否可拆分
                jsonObject.put("refund_state", newAddGoodRefundState.isChecked() ? 1 : 0);//是否允許退款
                jsonObject.put("exchange_state", newAddGoodExchangeState.isChecked() ? 1 : 0);//是否允許換貨
                JSONArray delivery_type = new JSONArray();
                if (newAddGoodDelivery1.isChecked()) {
                    delivery_type.put(1);
                }
                if (newAddGoodDelivery2.isChecked()) {
                    delivery_type.put(2);
                }
                if (newAddGoodDelivery3.isChecked()) {
                    delivery_type.put(3);
                }
                jsonObject.put("delivery_type", delivery_type);//快遞發貨方式
                jsonObject.put("delivery_template_id", storeFreightIndex == 0 ? "" : storeFreightList.get(storeFreightIndex).getId());//發貨模板id


                jsonObject.put("integral_mem_status", newAddGoodIntegralStatus.isChecked() ? 1 : 2);//購買獲得積分 門店參數
                jsonObject.put("integral", newAddGoodIntegral.getText().toString().trim());//會員消費送積分

                jsonObject.put("guide_royalty_state", newAddGoodGuideRoyaltyState.isChecked() ? 1 : 0);//購買該商品獲得提成的狀態 門店參數
                jsonObject.put("guide_royalty_custom_state", newAddGoodGuideRoyaltyCustom.isChecked() ? 1 : 0);//導購員獲得提成自定義狀態 門店參數
                jsonObject.put("guide_royalty_price", newAddGoodGuideRoyaltyPrice.getText().toString().trim());//導購員線下固定金提成 門店參數
                jsonObject.put("guide_royalty_online_price", newAddGoodGuideRoyaltyOnlinePrice.getText().toString().trim());//導購員線上固定金提成 門店參數
            }
            jsonObject.put("store_mem_status", newAddGoodStoreMemStatus.isChecked() ? 1 : 2);//是否開啓店內會員價
            jsonObject.put("store_mem_price", newAddGoodStoreMemPrice.getText().toString().trim());//店內會員價格
            jsonObject.put("store_mem_integral", newAddGoodStoreMemIntegral.getText().toString().trim());//店內會員所需積分
            jsonObject.put("shop_mem_status", newAddGoodShopMemStatus.isChecked() ? 1 : 2);//是否開啓商城會員價
            jsonObject.put("shop_mem_price", newAddGoodShopMemPrice.getText().toString().trim());//商城會員價格
            jsonObject.put("shop_mem_integral", newAddGoodShopMemIntegral.getText().toString().trim());//	商城會員價自定義營銷的積分
            jsonObject.put("plus_mem_status", newAddGoodPlusMemStatus.isChecked() ? 1 : 2);//plus會員價開關
            jsonObject.put("plus_price", newAddGoodPlusMemPrice.getText().toString().trim());//plus會員價
            jsonObject.put("plus_mem_integral", newAddGoodPlusMemIntegral.getText().toString().trim());//plus會員價自定義營銷的積分
            jsonObject.put("vip_retail_state", newAddGoodVipRetailState.isChecked() ? 1 : 0);//門店會員折扣
            jsonObject.put("vip_online_state", newAddGoodVipOnlineState.isChecked() ? 1 : 0);//商城會員折扣
            jsonObject.put("goods_img", goods_img);//商品封面圖
            jsonObject.put("goods_img_id", goods_image_id);//商品圖片id
            jsonObject.put("goods_video", "");//視頻簡介
            jsonObject.put("video_id", video_id);//商品視頻id
            jsonObject.put("details", "");//商品詳情
            jsonObject.put("attribute_state", newAddGoodIsSku.isChecked() ? 2 : 1);//是否開啓sku
            jsonObject.put("skuList", new Gson().toJson(skuGoodsList));
            jsonObject.put("simple_spelling", newAddGoodSpelling.getText().toString().trim());
            jsonObject.put("bannerList", bannerList);
            jsonObject = Tools.createParameterCode(jsonObject);
            HttpUtils.post(context, Common.OPERATE_GOODS_INFO, jsonObject, new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    loadingDialog.dismiss();
                    try {
                        JSONObject json = new JSONObject(text);
                        if (json.getInt("status") == 1) {
                            if (type == 1) {
                                finish();
                            } else {
                                finish();
                                intent = new Intent(context, NewAddGoodActivity.class);
                                startActivity(intent);
                                goods_img="";
                                goods_image_id="";
                                video_id="";
                                bannerList=new JSONArray();
                            }
                        }else {
                            Toast.makeText(context,json.getString("message"),Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                protected void onFailure(ResponseException e) {
                    loadingDialog.dismiss();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //獲取配送模板
    private void getStoreFreightTem() {
        HttpUtils.post(context, Common.GET_STORE_FREIGHT_TEM, Tools.createParameterCode(new JSONObject()), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                currencyInfo = GsonUtils.JsonToBean(text, CurrencyInfo.class);
                if (currencyInfo.getStatus() == 1) {
                    storeFreightList.add(new CurrencyInfo.DataBean("0", "請選擇配送模板", "請選擇配送模板", "請選擇配送模板"));
                    storeFreightList.addAll(currencyInfo.getData());
                    ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, storeFreightList) {
                        @Override
                        public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                            @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                            final TextView text = view.findViewById(R.id.drop_view);
                            text.setText(storeFreightList.get(position).getTitle());
                            return view;
                        }

                        @NonNull
                        @Override
                        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                            View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                            final TextView text = view.findViewById(R.id.spinner_tv);
                            text.setText(storeFreightList.get(position).getTitle());
                            return view;
                        }
                    };
                    newAddGoodDeliveryTemplate.setAdapter(arrayAdapter);

                    if (newGoodInfo!=null) {
                        if (!TextUtils.isEmpty(newGoodInfo.getGoods().getDelivery_template_id())) {
                            for (int i = 0; i < storeFreightList.size(); i++) {
                                if (storeFreightList.get(i).getId().equals(newGoodInfo.getGoods().getDelivery_template_id())) {
                                    newAddGoodDeliveryTemplate.setSelection(i);
                                    storeFreightIndex = i;
                                }
                            }
                        }
                    }
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    //獲取品牌庫
    private void getSelectBrand() {
        HttpUtils.post(context, Common.GET_SELECT_BRAND, Tools.createParameterCode(new JSONObject()), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                currencyInfo = GsonUtils.JsonToBean(text, CurrencyInfo.class);
                if (currencyInfo.getStatus() == 1) {
                    brandList.add(new CurrencyInfo.DataBean("0", "請選擇商品品牌", "請選擇商品品牌", "請選擇商品品牌"));
                    brandList.addAll(currencyInfo.getData());
                    ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, brandList) {
                        @Override
                        public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                            @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                            final TextView text = view.findViewById(R.id.drop_view);
                            text.setText(brandList.get(position).getName());
                            return view;
                        }

                        @NonNull
                        @Override
                        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                            View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                            final TextView text = view.findViewById(R.id.spinner_tv);
                            text.setText(brandList.get(position).getName());
                            return view;
                        }
                    };
                    newAddGoodBrand.setAdapter(arrayAdapter);

                    if (newGoodInfo!=null) {
                        if (!TextUtils.isEmpty(newGoodInfo.getGoods().getGoods_brand_id())) {
                            for (int i = 0; i < brandList.size(); i++) {
                                if (brandList.get(i).getId().equals(newGoodInfo.getGoods().getGoods_brand_id())) {
                                    newAddGoodBrand.setSelection(i);
                                    brandIndex = i;
                                }
                            }
                        }
                    }
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    //獲取標籤庫
    private void getGoodsLabelList() {
        HttpUtils.post(context, Common.GET_GOODS_LABEL_LIST, Tools.createParameterCode(new JSONObject()), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                try {
                    JSONObject object=new JSONObject(text);
                    if (object.getInt("status") == 1) {
                        labelList.add(new CurrencyInfo.DataBean("0", "請選擇標籤", "請選擇標籤", "請選擇標籤"));
                        String list=new JSONObject(object.getString("data")).getString("list");
                        JSONArray jsonArray=new JSONArray(list);
                        for (int i=0;i<jsonArray.length();i++){
                            CurrencyInfo.DataBean dataBean=GsonUtils.JsonToBean(jsonArray.get(i).toString(),CurrencyInfo.DataBean.class);
                            labelList.add(dataBean);
                        }
                        ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, labelList) {
                            @Override
                            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                                @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                                final TextView text = view.findViewById(R.id.drop_view);
                                text.setText(labelList.get(position).getName());
                                return view;
                            }

                            @NonNull
                            @Override
                            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                                View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                                final TextView text = view.findViewById(R.id.spinner_tv);
                                text.setText(labelList.get(position).getName());
                                return view;
                            }
                        };
                        newAddGoodLabel.setAdapter(arrayAdapter);

                        if (newGoodInfo!=null) {
                            if (!TextUtils.isEmpty(newGoodInfo.getGoods().getLabel_id())) {
                                for (int i = 0; i < labelList.size(); i++) {
                                    if (labelList.get(i).getId().equals(newGoodInfo.getGoods().getLabel_id())) {
                                        newAddGoodLabel.setSelection(i);
                                        labelIndex = i;
                                    }
                                }
                            }
                        }
                    }
                }catch (JSONException e){
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    //獲取單位庫
    private void getUnitSelect() {
        JSONObject jsonObject = new JSONObject();
        try {
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                if ("1".equals(aCache.getAsString("userType"))) {
                    jsonObject.put("managerType", 3);//3商戶 4門店
                } else {
                    jsonObject.put("managerType", 4);//3商戶 4門店
                }
            }
            HttpUtils.post(context, Common.GET_UNIT_SELECT, Tools.createParameterCode(new JSONObject()), new TextCallBack() {
                @Override
                protected void onSuccess(String text) {
                    try {
                        unitList.clear();
                        JSONObject object=new JSONObject(text);
                        if (object.getInt("status") == 1) {
                            unitList.add(new CurrencyInfo.DataBean("0", "請選擇單位", "請選擇單位", "請選擇單位"));
                            String list=new JSONObject(object.getString("data")).getString("list");
                            JSONArray jsonArray=new JSONArray(list);
                            for (int i=0;i<jsonArray.length();i++){
                                CurrencyInfo.DataBean dataBean=GsonUtils.JsonToBean(jsonArray.get(i).toString(),CurrencyInfo.DataBean.class);
                                unitList.add(dataBean);
                            }
                            ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, unitList) {
                                @Override
                                public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                                    @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                                    final TextView text = view.findViewById(R.id.drop_view);
                                    text.setText(unitList.get(position).getName());
                                    unitName=unitList.get(position).getName();
                                    return view;
                                }

                                @NonNull
                                @Override
                                public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                                    View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                                    final TextView text = view.findViewById(R.id.spinner_tv);
                                    text.setText(unitList.get(position).getName());
                                    unitName=unitList.get(position).getName();
                                    return view;
                                }
                            };
                            newAddGoodCompany.setAdapter(arrayAdapter);

                            if (newGoodInfo!=null) {
                                if (!TextUtils.isEmpty(newGoodInfo.getGoods().getCompany())) {
                                    for (int i = 0; i < unitList.size(); i++) {
                                        if (unitList.get(i).getName().equals(newGoodInfo.getGoods().getCompany())) {
                                            newAddGoodCompany.setSelection(i);
                                            unitIndex = i;
                                            unitName = unitList.get(i).getName();
                                            Message message=new Message();
                                            message.what=2;
                                            message.obj=unitList.get(i).getName();
                                            handler.sendMessage(message);
                                        }
                                    }
                                }
                            }
                        }
                    }catch (JSONException e){
                        e.printStackTrace();
                    }

                }

                @Override
                protected void onFailure(ResponseException e) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //商品產地
    private void getGoodsYieldlyList() {
        HttpUtils.post(context, Common.GET_GOODS_YIELDLY_LIST, Tools.createParameterCode(new JSONObject()), new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                currencyInfo = GsonUtils.JsonToBean(text, CurrencyInfo.class);
                if (currencyInfo.getStatus() == 1) {
                    yieldlyList.add(new CurrencyInfo.DataBean("0", "請選擇產地", "請選擇產地", "請選擇產地"));
                    yieldlyList.addAll(currencyInfo.getData());
                    ArrayAdapter arrayAdapter = new ArrayAdapter(context, R.layout.item_select, yieldlyList) {
                        @Override
                        public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                            @SuppressLint("ViewHolder") View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_drop, parent, false);
                            final TextView text = view.findViewById(R.id.drop_view);
                            text.setText(yieldlyList.get(position).getName());
                            return view;
                        }

                        @NonNull
                        @Override
                        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                            View view = ((Activity) context).getLayoutInflater().inflate(R.layout.item_select, parent, false);
                            final TextView text = view.findViewById(R.id.spinner_tv);
                            text.setText(yieldlyList.get(position).getName());
                            return view;
                        }
                    };
                    newAddGoodYieldly.setAdapter(arrayAdapter);

                    if (newGoodInfo!=null) {
                        if (!TextUtils.isEmpty(newGoodInfo.getGoods().getGoods_yieldly_id())) {
                            for (int i = 0; i < yieldlyList.size(); i++) {
                                if (yieldlyList.get(i).getId().equals(newGoodInfo.getGoods().getGoods_yieldly_id())) {
                                    newAddGoodYieldly.setSelection(i);
                                    yieldlyIndex = i;
                                }
                            }
                        }
                    }
                }
            }

            @Override
            protected void onFailure(ResponseException e) {

            }
        });
    }

    /*頁面回調*/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode != 1 && requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {//掃描結果回調
            Bundle bundle = data.getExtras();
            newAddGoodCode.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
        }
        switch (requestCode) {
            /*case Constant.REQ_QR_CODE:
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    addGoodsBarcodeEdit.setText(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                    getGoodName(bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN));
                }
                break;*/
            case 100:
                if (data != null) {
                    newAddGoodClassificationName.setText(data.getStringExtra("name"));
                    classId = data.getStringExtra("id");
                }
                break;
        }

    }
    List<SkuInfoNew> skuInfoNews=new ArrayList<>();
    @Override
    public void backSkuGoodsList(List<SkuGoodsInfo> list, List<SkuInfoNew> skuInfoNewList) {
        skuGoodsList.clear();
        skuGoodsList.addAll(list);
        Log.d("規格數量",String.valueOf(skuGoodsList.size()));
        setSkuGoodsAdapter();
        skuInfoNews=skuInfoNewList;
        if (skuGoodsList.size() > 0) {
            newAddGoodSkuGoodsLin.setVisibility(View.VISIBLE);
//            addGoodsSkuGoodsView.setVisibility(View.VISIBLE);
        } else {
            newAddGoodSkuGoodsLin.setVisibility(View.GONE);
//            addGoodsSkuGoodsView.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化或者刷新  初始化規格設置中listView
     */
    private SkuGoodsAdapter skuGoodsAdapter;

    private void setSkuGoodsAdapter() {
        if (skuGoodsAdapter == null) {
            skuGoodsAdapter = new SkuGoodsAdapter(context, skuGoodsList,titleTitle.getText().toString().trim().equals("編輯商品"));
            skuGoodsAdapter.setmStatus(newAddGoodShopMemStatus.isChecked(),
                    newAddGoodStoreMemStatus.isChecked(),newAddGoodPlusMemStatus.isChecked());
            skuGoodsAdapter.setIsSerial(newAddGoodIsSerial.isChecked());
            skuGoodsAdapter.setIsWeight(newAddGoodIsWeight.isChecked());
            newAddGoodSkuGoodsListView.setAdapter(skuGoodsAdapter);
            skuGoodsAdapter.setGuide(newAddGoodGuideRoyaltyCustom.isChecked());
            skuGoodsAdapter.setshowSet(editSet);
        } else {
            skuGoodsAdapter.notifyDataSetChanged();
        }

    }

//    private void setEdit1(final EditText edit1) {
//        edit1.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//
//            }
//
//            @Override
//            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                String temp = edit1.getText().toString();
//                int posDot = temp.indexOf(".");
//                if (posDot <= 0) return;
//                if (temp.length() - posDot - 1 > 2) {
//                    edit1.setText(temp.substring(0,posDot+3));
//                }
//            }
//
//            @Override
//            public void afterTextChanged(Editable editable) {
////                if (edit1==newAddGoodWeightValue){
////                    newAddGoodIsWeight.setFocusable(false);
////                    newAddGoodIsWeight.setClickable(false);
////                }
//
//            }
//        });
//    }

    private void uploadFile(int paramInt, File paramFile,List<LocalMedia> result) {
        tint.setText("上傳中");
//        loadingDialog.show();
        JSONObject jSONObject = new JSONObject();
        try {
            jSONObject.put("fileType", paramInt);
            jSONObject.put("user_type", aCache.getAsString("userType"));
            jSONObject.put("operate_id", aCache.getAsString("operate_id"));
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        HttpUtils.postAndFile(context, Common.UPLOAD_FILE, Tools.createParameterCode(jSONObject), paramFile, paramInt, new TextCallBack() {
            @Override
            protected void onFailure(ResponseException param1ResponseException) {
                loadingDialog.dismiss();
                Log.d("視頻返回值",param1ResponseException.getMessage());
            }

            @Override
            protected void onSuccess(String param1String) {
                try {
                    Message message=new Message();
                    message.what=5;
                    message.obj="上傳成功";
                    handler.sendMessage(message);
                    JSONObject jSONObject = new JSONObject(param1String);
                    Toast.makeText(context,jSONObject.getString("msg"),Toast.LENGTH_SHORT).show();
                    if (jSONObject.getInt("status") == 1) {
                        switch (imageType) {
                            case 1:
                                goods_img = jSONObject.getString("access_path");
                                goods_image_id = jSONObject.getString("image_id");
                                mAdapter.setList(result);
                                mAdapter.notifyDataSetChanged();
                                break;
                            case 2:
                                video_id = jSONObject.getString("image_id");
                                mAdapter2.setList(result);
                                mAdapter2.notifyDataSetChanged();
                                break;
                            case 3:
                                JSONObject jSONObject1 = new JSONObject();
                                jSONObject1.put("image_id", jSONObject.getString("image_id"));
                                jSONObject1.put("image", jSONObject.getString("access_path"));
                                bannerList.put(jSONObject1);
                                mAdapter3.setList(result);
                                mAdapter3.notifyDataSetChanged();
                                break;
                            default:
                                break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
